Hibernate中的DataBase加密

Cha*_*har 1 java database hibernate

使用hibernate时如何加密数据库字段?

我们开发了一些客户正在使用该应用程序的产品有些客户端询问数据库加密是否有可能在应用程序级别加密数据而代码中没有更多更改.

请尽快给我建议.

And*_*esi 11

试试这个:

在您的实体中放置一个属性:

private byte[]  encryptedBody;
Run Code Online (Sandbox Code Playgroud)

使用此getter和setter:

@Column(columnDefinition= "LONGBLOB", name="encryptedBody") 
@ColumnTransformer(
  read="AES_DECRYPT(encryptedBody, 'yourkey')", 
  write="AES_ENCRYPT(?, 'yourkey')")
public byte[]  getEncryptedBody() {
    return encryptedBody;
}

public void setEncryptedBody(byte[]  encryptedBody) {
    this.encryptedBody = encryptedBody;
}
Run Code Online (Sandbox Code Playgroud)

然后当您重新使用列时:

private final Charset UTF8_CHARSET = Charset.forName("UTF-8");

String decodeUTF8(byte[] bytes) {
    return new String(bytes, UTF8_CHARSET);
}

String s = decodeUTF8(entity.getEncryptedBody());
Run Code Online (Sandbox Code Playgroud)

请注意:AES_DECRYPT和AES_ENCRYPT属于MySQL.如果您有不同的数据库引擎,请找到类似的功能.

希望这可以帮助.

  • 跨数据库使用技巧-您可以创建存储的proc(或函数)来为您处理加密和解密,然后通过@ColumnTransformer批注进行调用。因此,当您必须移植到另一个数据库时,只需在数据库本身中实现它们即可,而bob是您的叔叔。 (2认同)

Vla*_*cea 7

@ColumnTransformer您可以像这样使用注释:

@ColumnTransformer(
    read =  "pgp_sym_decrypt(" +
            "    storage, " +
            "    current_setting('encrypt.key')" +
            ")",
    write = "pgp_sym_encrypt( " +
            "    ?, " +
            "    current_setting('encrypt.key')" +
            ") "
)
@Column(columnDefinition = "bytea")
private String storage;
Run Code Online (Sandbox Code Playgroud)

这样,Hibernate 将能够在持久或合并实体属性时对其进行加密,并在读取实体时对其进行解密。