字段加密(Client-Side Field Level Encryption) 是 MongoDB 4.2 重要新功能。现对其进行测试如下:
MongoDB 4.2 字段加密 key 支持 Local 和 AWS 的 KMS. 官网文档主要是AWS KMS 的例子,本次测一下Local 方式。

本地生成 96位BASE64编码 key 字符串

$ openssl rand -base64 96
U7w7Mp0tnFVyu2+vvJ7cLc8tWB4ml8YX2ccJmzlggmJYk7Gb1bWYynlXiNGF4Cba
UyXwRf8XI4RRpc8EkSQfAhOAaNEdiXumHrHKm+Q8w6eVZXJdNh3bVTi4yeUZTF15

在 MongoDB 中创建 key, 根据key的UUID去加密

PRIMARY> clientSideFLEOptions = {
  "keyVaultNamespace" : "encryption.dataKeys",
  "kmsProviders" : {
      "local" : {
      "key" : BinData(0,"U7w7Mp0tnFVyu2+vvJ7cLc8tWB4ml8YX2ccJmzlggmJYk7Gb1bWYynlXiNGF4CbaUyXwRf8XI4RRpc8EkSQfAhOAaNEdiXumHrHKm+Q8w6eVZXJdNh3bVTi4yeUZTF15")
     }
  }
}
PRIMARY> encryptedClient = Mongo(
  "mongodb://testdb_rw:12345678@127.0.0.1:27017/testdb?replSetName=usersecurity",
  clientSideFLEOptions
)
PRIMARY> keyVault = encryptedClient.getKeyVault();
PRIMARY> keyVault.createKey("local", "kms:ccj", [ "field-encryption-key" ])
PRIMARY> keyVault.getKeyByAltName("field-encryption-key")
{ "_id" : UUID("8765a807-fb2c-4aeb-88d4-6fa0b3ec127b"), "keyMaterial" : BinData(0,"vV3NP8bGOKrT0ghF8oLoRx/74mtQnJA4VjtLKvaz4h3V/klRsIOYcfUfJXeCH8kt2Yi73Qi2pN9SmW1CDTExMxtIxRADyyp+b0lLCNRbIVmNeUbpSz2ZrYSGwj2+Ai1nQT0RhLh0Fl4WtLS2NCxcRsrxEgkKw7TJPEgduXX4qz4PMm7obVlDhIqVjbAB0Ksf2pH8iDgtn3q++Sjs4ydfwQ=="), "creationDate" : ISODate("2019-09-25T05:57:41.386Z"), "updateDate" : ISODate("2019-09-25T05:57:41.386Z"), "status" : 0, "version" : NumberLong(0), "masterKey" : { "provider" : "local" }, "keyAltNames" : [ "field-encryption-key" ] }

PRIMARY> encryptedClient.encrypt(
...   UUID("8765a807-fb2c-4aeb-88d4-6fa0b3ec127b"),
...   "13899999999",
...   "AEAD_AES_256_CBC_HMAC_SHA_512-Random"
... )
BinData(6,"AodlqAf7LErriNRvoLPsEnsCn9Cxgf6MhtobYqIC/weBVN+3OKub0ud9AwpHq5rXl+q0wWb9MRQBr4E7LW6npc0xYbDg2mwK09M8+/tcqszLHk30AUaVy3W0yULnjAQMHpk=")

PRIMARY> encryptedClient.decrypt(BinData(6,"AodlqAf7LErriNRvoLPsEnsCn9Cxgf6MhtobYqIC/weBVN+3OKub0ud9AwpHq5rXl+q0wWb9MRQBr4E7LW6npc0xYbDg2mwK09M8+/tcqszLHk30AUaVy3W0yULnjAQMHpk="))
13899999999


PRIMARY> db.user.insert({phone:encryptedClient.encrypt( UUID("8765a807-fb2c-4aeb-88d4-6fa0b3ec127b"),  "13899999999","AEAD_AES_256_CBC_HMAC_SHA_512-Random")})
PRIMARY> encryptedClient.decrypt(db.user.findOne().phone)
13899999999
0 回复
需要 登录 后方可回复, 如果你还没有账号你可以 注册 一个帐号。