Spring Boot MongoDB 使用加密字段

Posted

技术标签:

【中文标题】Spring Boot MongoDB 使用加密字段【英文标题】:Spring boot MongoDB working with encrypted fields 【发布时间】:2021-12-10 18:37:54 【问题描述】:

我有一个 spring boot 项目(版本 2.5.5),我正在使用 spring-boot-starter-data-mongodb 依赖项来处理 MongoDB。

我有一个包含这些字段的 bean:

@Document(collection = "user_data")
public class UserData 
 @Id
 private String id;
 @Field("is_active")
 private Boolean isActive;
 @Field("organization_id")
 private String organizationId;
 @Field("system_mode")
 private SystemMode systemMode;
 @Field("first_name")
 private String firstName;
 @Field("last_name")
 private String lastName;

*还有构造函数、getter 和 setter,但为简单起见,我省略了它们。

我也有一个匹配的存储库:

@Repository
  public interface UsersDataRepository extends MongoRepository<UserData, String> 

现在 firstNamelastName 字段实际上已加密并以二进制类型存储在数据库中。

当我试着说

Optional<UserData> optionalUserData = usersDataRepository.findById(userId);

我收到一条错误消息,指出无法从二进制转换为字符串,这是有道理的,因为字段已加密。

在数据库中,我有一个 key_vault 集合,其中包含要解密的密钥。

那么如何使用上述设置添加 MongoDB 客户端字段级别解密,以便我可以解密字段并在我的项目中使用它们?

【问题讨论】:

【参考方案1】:

使用 MongoDB GridFsTemplate 保存、检索和删除二进制文件。 https://www.youtube.com/watch?v=7ciWYVx3ZrA&t=1267s

【讨论】:

【参考方案2】:

我按照本指南为我的案例找到了一个可行的解决方案: https://blog.contactsunny.com/tech/encrypting-and-decrypting-data-in-mongodb-with-a-springboot-project

简而言之,创建一个处理加密和解密字段的组件。 创建两个事件监听器类,它们将监听 mongo 保存并从数据库事件中获取。

我的 MongoDBAfterLoadEventListener 是这样结束的, 请注意,它目前仅适用于字符串:

public class MongoDBAfterLoadEventListener extends AbstractMongoEventListener<Object> 

    @Autowired
    private EncryptionUtil encryptionUtil;

    @Override
    public void onAfterLoad(AfterLoadEvent<Object> event) 

        Document eventObject = event.getDocument();
        
        List<String> keysToDecrypt = encryptionUtil.ENCRYPTED_FIELDS_MAP.get(event.getCollectionName());
        
        if (keysToDecrypt == null || keysToDecrypt.isEmpty()) 
            return;
        

        for (String key : eventObject.keySet()) 
            if (keysToDecrypt.contains(key)) 
                Binary encrypted = (Binary) eventObject.get(key);
                BsonBinary bsonBinary = new BsonBinary(encrypted.getData());
                BsonValue decrypted = this.encryptionUtil.decryptText(bsonBinary);
                eventObject.put(key, decrypted.asString().getValue());
            
        

        super.onAfterLoad(event);
    

【讨论】:

以上是关于Spring Boot MongoDB 使用加密字段的主要内容,如果未能解决你的问题,请参考以下文章

spring boot系列spring boot 使用mongodb

Spring Boot:Spring Boot 中 MongoDB 的使用

如何在 spring-boot 中禁用 spring-data-mongodb 自动配置

如何使用Spring框架加密文档中的所有MongoDB字段

如何避免使用 Spring-Boot 下载嵌入式 MongoDb

Spring Boot加密属性文件数据