Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

mysql - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...