问题描述
我有一个表mm,其中包含字段ID,名称和Sal
我使用AES_ENCRYPT在数据库中插入了加密值
psmt = con.prepareStatement("insert into mm values("+id+",AES_ENCRYPT('"+name+"','"+key+"'),AES_ENCRYPT('"+sal+"','"+key+"'))");
它正常工作
但是当我尝试使用AES_DECRYPT检索这些值时
rs = st.executeQuery("select id,AES_DECRYPT(name,'"+key+"'),AES_DECRYPT(sal,'"+key+"') FROM mm WHERE id="+rs.getInt(1)+"");
当我在mysql控制台上应用查询时,它可以正常工作.
但是当使用Java代码应用时,它会给出
之类的值| 1| [B@1f0690a| [B@803365 |
为什么我得到这些值而不是原始值?
字节数组上的toString()
不会返回字节数组的内容,而是返回[B@
并后跟字节数组的标识哈希码.在插入中,您没有使用key
的内容作为键,而是使用了toString
值.您需要将PreparedStatement
与参数化查询一起使用,并使用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);
对您选择的查询执行相同的操作.
永远不要将值连接到查询中.它将使您容易受到SQL注入的攻击.
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.
这篇关于使用Java的AES_ENCRYPT和AES_DECRYPT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!