How to implement data encryption at rest for Mongo

2019-07-09 20:48发布

问题:

I've gone through MongoDB docs that explain how to configure encryption which is available in MongoDB Enterprise only.

How to implement data at rest in MongoDB Community Edition v3.4?

回答1:

I was asking the same question to myself just few month ago. This is a list of options I have found so far:

  • encrypt storage volumes on the file system level. It is what Atlas offers, and most of cloud providers support: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html, https://docs.microsoft.com/en-us/azure/security-center/security-center-disk-encryption to name a few. Combined with cloud key management it is the simplest way IMHO. The same can be achieved for on-premises storages for most operation systems. Please ask how to do that in relevant StackExchange community providing enough details about underlying OS.
  • Percona MongoDB server has some enterprise features, including audit and encryption. IIRC it uses disk encryption provided by OS, so it's basically the same as the previous one.
  • encrypt sensitive data on application level. e.g. https://www.openssl.org/docs/manmaster/man1/rsautl.html. It is a bit more flexible, but you will loose some features like full text search and sorting index on encrypted fields.
  • buy enterprise license. Does not answer the question directly, yet may be more cost-efficient comparing to the previous options.


回答2:

Like Alex Blex suggested, you have other options than Community Edition.

However, if you still want to go with Community Edition,

You can use mongoose.js for interacting with mongoDB. It has getters and setters that can fulfill your requirement:
http://mongoosejs.com/docs/2.7.x/docs/getters-setters.html

In your mongoose schema, you can specify get and set functions for fields.

var mySchema = new Schema({
    name: {
        type: String,
        default: '',
        trim: true,
        required: 'Please enter group name',
        unique: true,
        get: decryptFunction,
        set: encryptFunction
    }
});
mySchema.set('toObject', {getters: true});
mySchema.set('toJSON', {getters: true});

The set will be executed whenever you are assigning any value to the field. It will take the value as a parameter, and then you can write your own encryption logic.

The get will be executed whenever you access the field's value. It will get the encrypted value as a parameter and you can write your decryption logic there.

You will have to write the decryptFunction and encryptFunction.

However, you wont be able to query those fields with original values. As the mongodb does not know the text is encrypted.