开发者

DataBase encryption in Hibernate

How can encrypt the data base fields when using the hibernate?

We have developed the product some of the clients are using that application Some clients is asking about the data base encryption Is there any possible to encrypt the data in application level with out more changes in the c开发者_Python百科ode.

Please give me the suggestion as soon as possible.


Try this:

Put an attribute in your entity:

private byte[]  encryptedBody;

Use this getter and setters:

@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;
}

And then when you retrive the column use:

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

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

String s = decodeUTF8(entity.getEncryptedBody());

BEWARE: AES_DECRYPT and AES_ENCRYPT belong to MySQL. If you have a different data base engine find similar functions.

Hope this helps.


You can use the @ColumnTransformer annotation like this:

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

This way, Hibernate will be able to encrypt the entity attribute when you persist or merge it and decrypt it when you read the entity.


I think that you are looking for column transformers. You can find how to do it in the Hibernate reference:

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-column-read-and-write

I hope that helps!


You could use jasypt. It has an Hibernate integration that allows you to encrypt properties while saving (and decrypt while loading).

http://www.jasypt.org/hibernate.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜