1 / 1
Oct 2024

My application is using a local masterkey to decrypt my datas in mongodb server… I am planning to rotate my keyfile once a year like manually triggering a separate API to do it.

So using the below code im trying to create a new local masterkey file and re-encrypt the DEK in my keyVault collection. I tried in both java-8 and Node.js (Using Mongosh-2.3.1)… But both fails with the same error. Not sure if my below implementation is correct…

Refered their sample from here

Using mongodb-driver-sync-5.0.0 and mongodb-crypt-1.8.0

kmsProviders.put("local", newlyCreatedMasterKey); ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder() .keyVaultMongoClientSettings(MongoClientSettings.builder() .applyConnectionString(new ConnectionString(connectionString)) .build()) .keyVaultNamespace(keyVaultDb+"."+keyVaultColl) .kmsProviders(kmsProviders) .build(); MongoCollection<Document> keyVault = mongoClient.getDatabase(keyVaultDb).getCollection(keyVaultColl); for (Document dataKeyDoc : keyVault.find()) { Binary id = dataKeyDoc.get("_id", Binary.class); BsonBinary dataKeyId = new BsonBinary(id.getType(), id.getData()); clientEncryption.rewrapManyDataKey( Filters.eq("_id", dataKeyId), new RewrapManyDataKeyOptions() .provider("local") .masterKey(new BsonDocument("key", new BsonBinary(newlyCreatedMasterKey))) ); }

Using Node.js (Mongosh-2.3.1)

// Creating a new key const key = require("crypto").randomBytes(96); fs.writeFileSync('keyfile.txt', key); // Connection options var autoEncryptionOpts = { "keyVaultNamespace" : "encryption.__keyvault", "kmsProviders" : { "local" : { "key" : BinData(0, key.toString("base64")) } } } // Created the encrypted client const client = new Mongo(uri, autoEncryptionOpts); const keyVault = client.getKeyVault(); const result = keyVault.rewrapManyDataKey({}, { provider: 'local', masterKey: { keyMaterial: BinData(0, key.toString("base64")) } })

Both way returns the same error as below

Error rewrapping data keys: Unexpected field: 'key' Exception in thread "main" com.mongodb.MongoClientException: Exception in encryption library: Unexpected field: 'key' at com.mongodb.client.internal.Crypt.wrapInMongoException(Crypt.java:375) at com.mongodb.client.internal.Crypt.rewrapManyDataKey(Crypt.java:260) at com.mongodb.client.internal.ClientEncryptionImpl.rewrapManyDataKey(ClientEncryptionImpl.java:173) at RotateMasterKey.reEncryptDataKeys(RotateMasterKey.java:122) at RotateMasterKey.main(RotateMasterKey.java:56) Caused by: com.mongodb.crypt.capi.MongoCryptException: Unexpected field: 'key' at com.mongodb.crypt.capi.MongoCryptContextImpl.throwExceptionFromStatus(MongoCryptContextImpl.java:156) at com.mongodb.crypt.capi.MongoCryptImpl.configure(MongoCryptImpl.java:376) at com.mongodb.crypt.capi.MongoCryptImpl.createRewrapManyDatakeyContext(MongoCryptImpl.java:311) at com.mongodb.client.internal.Crypt.rewrapManyDataKey(Crypt.java:251) ... 3 more