简体   繁体   English

使用Java的AES_ENCRYPT和AES_DECRYPT

[英]AES_ENCRYPT and AES_DECRYPT using java

I have table mm with field id,name and sal 我有表mm,其中包含字段ID,名称和Sal

I inserted encrypted value in the DB using the AES_ENCRYPT 我使用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 但是当我尝试使用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. 当我在mysql控制台上应用查询时,它可以正常工作。

but when apply using java code it gives values like 但是当使用Java代码应用时,它给出的值如下

| 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. 字节数组上的toString()不会返回字节数组的内容,而是[B@后跟字节数组的标识哈希码。 In your insert you did not use the content of key as the key, but the toString -value. 在您的插入内容中,您没有使用key的内容作为key,而是使用toString -value。 You need to use a PreparedStatement with a parametrized query, and set the values using setBytes : 您需要对参数化查询使用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);

And do the same for your select query. 并对您选择的查询执行相同的操作。

You should never concatenate values into your query. 您永远不应将值连接到查询中。 It will make you vulnerable to SQL injection. 这将使您容易受到SQL注入的攻击。

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. 其次,使用AES_DECRYPT解密这两列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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