【问题标题】:Spring boot MongoDB working with encrypted fieldsSpring Boot MongoDB 使用加密字段
【发布时间】: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 客户端字段级别解密,以便我可以解密字段并在我的项目中使用它们?

【问题讨论】:

    标签: java spring mongodb spring-boot encryption


    【解决方案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);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-07
        • 1970-01-01
        • 2021-10-20
        • 2015-05-10
        • 1970-01-01
        • 2015-11-16
        • 2022-06-17
        • 1970-01-01
        相关资源
        最近更新 更多