简体   繁体   中英

AES_ENCRYPT and AES_DECRYPT using java

I have table mm with field id,name and sal

I inserted encrypted value in the DB using the AES_ENCRYPT

psmt = con.prepareStatement("insert into mm values("+id+",AES_ENCRYPT('"+name+"','"+key+"'),AES_ENCRYPT('"+sal+"','"+key+"'))");

It is working properly

but when i am trying to retrieve these values using AES_DECRYPT

rs = st.executeQuery("select id,AES_DECRYPT(name,'"+key+"'),AES_DECRYPT(sal,'"+key+"') FROM mm WHERE id="+rs.getInt(1)+"");

When i am applying query on mysql console it work properly.

but when apply using java code it gives values like

| 1| [B@1f0690a| [B@803365 |

Why i am getting these values instead of the original values ?

A toString() on a byte-array does not return the content of the byte array, but [B@ followed by the identity hashcode of the byte array. In your insert you did not use the content of key as the key, but the toString -value. You need to use a PreparedStatement with a parametrized query, and set the values using setBytes :

psmt = con.prepareStatement("insert into mm values (?, AES_ENCRYPT(?, ?), AES_ENCRYPT(?, ?))");
psmt.setInt(1, id);
psmt.setString(2, name);
psmt.setBytes(3, key);
psmt.setstring(4, sal);
psmt.setBytes(5, key);

And do the same for your select query.

You should never concatenate values into your query. It will make you vulnerable to SQL injection.

Change your process sequence.

First, just select your value from table.

From your eg. --> | 1| [B@1f0690a| [B@803365 |

Second, decrypt these two column using AES_DECRYPT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM