How to encrypt a field in MongoDB

I need to encrypt one field in a mongo document. What is the best way to do this? I am using spring. Is there a spring annotation for it?

+6
source share
3 answers

encryption can be performed at the moment only from java. here you have the same question asked last month

this is already done in ruby, so if you want to use jruby for this in your project, look at this

or you can wait until MongoDB includes this in its API

+1
source

You can use this library, which adds support for @Encrypted annotation fields:

<dependency> <groupId>com.bol</groupId> <artifactId>spring-data-mongodb-encrypt</artifactId> <version>1.0.1</version> </dependency> 

To configure spring:

 @Bean public CryptVault cryptVault() { return new CryptVault() .with256BitAesCbcPkcs5PaddingAnd128BitSaltKey(0, oldKey) .with256BitAesCbcPkcs5PaddingAnd128BitSaltKey(1, secretKey) // can be omitted if it the highest version .withDefaultKeyVersion(1); } @Bean public EncryptionEventListener encryptionEventListener(CryptVault cryptVault) { return new EncryptionEventListener(cryptVault); } 

And use it:

 @Document public class MyBean { @Id public String id; // not encrypted @Field public String nonSensitiveData; // encrypted primitive types @Field @Encrypted public String secretString; @Field @Encrypted public Long secretLong; // encrypted sub-document (MySubBean is serialized, encrypted and stored as byte[]) @Field @Encrypted public MySubBean secretSubBean; // encrypted collection (list is serialized, encrypted and stored as byte[]) @Field @Encrypted public List<String> secretStringList; // values containing @Encrypted fields are encrypted @Field public MySubBean nonSensitiveSubBean; // values containing @Encrypted fields are encrypted @Field public List<MySubBean> nonSensitiveSubBeanList; // encrypted map (values containing @Encrypted fields are replaced by encrypted byte[]) @Field public Map<String, MySubBean> publicMapWithSecretParts; } public class MySubBean { @Field public String nonSensitiveData; @Field @Encrypted public String secretString; } 

For more information, visit the project website.

+2
source

You can use your own encryption scheme and save it in the database. In rails, this will be easy to do.

  include Mongoid::Document field :encrypted_me, type: String, encrypted: true 

If you can describe which platform you are using, this will make some explanation.

-1
source

Source: https://habr.com/ru/post/988770/


All Articles