I am using MongoDB client-side field level encryption to encrypt and decrypt data. However, I noticed that every time I execute the program, the primitive binary key changes. This makes it difficult for me to retrieve previously encrypted data because I cannot decrypt it using the new key.
Is there a way to maintain a consistent encryption key for client-side field level encryption in MongoDB? If so, how can I do it?
https://go.dev/play/p/6W8e0OiPV2L
I'm trying to implement client-side field level encryption in my MongoDB Community project to encrypt certain fields in my documents before storing them in the database, and then decrypt them when I retrieve them from the database.
I've been following the MongoDB documentation and was able to successfully encrypt and decrypt the data during the first execution of my program. However, I noticed that the key keeps changing every time I run the program again, and I want to keep the key stationary.
These lines should be removed:
// Drop the Key Vault Collection in case you created this collection
// in a previous run of this application.
if err = Client.Database(keyVaultDb).Collection(keyVaultColl).Drop(context.TODO()); err != nil {
log.Fatalf("Collection.Drop error: %v", err)
}
And the following lines are needed only when the key does not exist yet:
dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), provider, dataKeyOpts)
if err != nil {
log.Fatalf("CreateDataKey error: %v", err)
}
Maybe do a clientEnc.GetKeyByAltName
call first to check whether the key exists.
By saying "the primitive binary key changes", I think you meant the Data Encryption Key (DEK) changes. That's caused by the dropping of the collection that stores the DEK.
See Keys and Key Vaults:
A Customer Master Key (CMK) is the key you use to encrypt your Data Encryption Keys (DEK)....
A Data Encryption Key (DEK) is the key you use to encrypt the fields in your MongoDB documents. You store your Data Encryption Key in your Key Vault collection encrypted with your CMK....
If you delete a Data Encryption Key (DEK), all fields encrypted with that DEK become permanently unreadable.
If you delete a CMK, all fields encrypted with DEKs encrypted with that CMK become permanently unreadable.