我在我的 Spring Boot 应用程序中实现了一个自定义 AttributeConverter 类,它使用 AES 密码和密钥加密和解密我实体的某些字段。 这是我的转换器类:
@Converter
public class DataEncryptionConverter implements AttributeConverter<Object, String> {
@Value("${encryption.key}")
private String encryptionKey;
private final String encryptionCipher = "AES";
private Key key;
private Cipher cipher;
private Key getKey(){
if(key == null){
key = new SecretKeySpec(encryptionKey.getBytes(), encryptionCipher);
}
return key;
}
private Cipher getCipher() throws GeneralSecurityException {
if(cipher == null){
cipher = Cipher.getInstance(encryptionCipher);
}
return cipher;
}
private void initCipher(int encryptMode) throws GeneralSecurityException{
getCipher().init(encryptMode, getKey());
}
@SneakyThrows
@Override
public String convertToDatabaseColumn(Object attribute) {
if (attribute == null) {
return null;
}
initCipher(Cipher.ENCRYPT_MODE);
byte[] bytes = SerializationUtils.serialize(attribute);
return Base64.getEncoder().encodeToString(getCipher().doFinal(bytes));
}
@SneakyThrows
@Override
public Object convertToEntityAttribute(String dbData) {
if (dbData == null) {
return null;
}
initCipher(Cipher.DECRYPT_MODE);
byte[] bytes = getCipher().doFinal(Base64.getDecoder().decode(dbData));
return SerializationUtils.deserialize(bytes);
}
}
我用在我要加密的字段上:
public Class Task{
@Convert(converter = DataEncryptionConverter.class)
private String task_title;
@Convert(converter = DataEncryptionConverter.class)
private String task_description;
}
我想在我的 PostgreSQL 数据库中运行一个选择查询以查看解密形式的结果。我怎样才能做到这一点?
我试过以下但出现错误:
SELECT convert_from(decode(PGP_SYM_DECRYPT(decode(task_title, 'base64'), 'encryption-key'), 'escape'), 'UTF8') as decrypted_title FROM task;
我得到这个错误:错误的密钥或损坏的数据
SELECT convert(decode(PGP_SYM_DECRYPT(decode(task_title, 'base64'), 'encryption-key'), 'escape'), 'UTF8') as decrypted_title FROM task;
我得到这个错误:
函数转换(bytea,未知)不存在 第 1 行:选择转换(解码(PGP_SYM_DECRYPT(解码(task_title,'ba ...
我在这里做错了什么?任何帮助将不胜感激。