我有一個 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> {
}
現在欄位firstName和lastName實際上已加密并以二進制型別存盤在資料庫中。
當我試著做說
Optional<UserData> optionalUserData = usersDataRepository.findById(userId);
我收到一個錯誤,指出無法從二進制轉換為字串,這是有道理的,因為欄位是加密的。
在資料庫中,我有一個 key_vault 集合,其中包含要解密的密鑰。
那么如何使用上述設定添加 MongoDB 客戶端欄位級解密,以便我可以解密欄位并在我的專案中使用它們?
uj5u.com熱心網友回復:
我按照本指南為我的案例找到了一個可行的解決方案:https : //blog.contactsunny.com/tech/encrypting-and-decrypting-data-in-mongodb-with-a-springboot-project
簡而言之,創建一個組件來處理加密和解密欄位。創建兩個事件偵聽器類,它們將偵聽 mongo save 并從資料庫事件中獲取。
我的 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);
}
}
uj5u.com熱心網友回復:
使用 MongoDB GridFsTemplate 來保存、檢索和洗掉二進制檔案。https://www.youtube.com/watch?v=7ciWYVx3ZrA&t=1267s
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/336939.html
