为什么解密函数会将所有值都改为null?

m3eecexj  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(318)

我正在尝试加密所有公司数据。但是当我想要解密它们时,我只会看到空值。我在加密后检查了我的数据,它看起来是加密的。
这是我的密码

update TCB set Company=aes_encrypt(Company,'1234') WHERE Company= CONVERT(Company USING ASCII);
//I added where clause in case if there is any Encrypted data

select *,cast(aes_decrypt(Company,'1234') as char(100))  from TCB;

提前谢谢

lpwwtiir

lpwwtiir1#

AES_ENCRYPT() 返回二进制字节,而不是文本。当您将加密的数据保存到同一列(我假设该列是带有字符集的varchar或text列)时,它试图将二进制字节解释为该列字符集中的编码。很可能许多字节都不是该字符集的有效编码,因此最终会产生无法解密的垃圾数据。

mysql> create table tcb ( company text );

mysql> insert into tcb set company = 'company';

mysql> update tcb set company = aes_encrypt(company, '1234');
Query OK, 1 row affected, 1 warning (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> show warnings;
+---------+------+----------------------------------------------------------------------------------+
| Level   | Code | Message                                                                          |
+---------+------+----------------------------------------------------------------------------------+
| Warning | 1366 | Incorrect string value: '\x8F\x94O\x1D\xB9\x07...' for column 'company' at row 1 |
+---------+------+----------------------------------------------------------------------------------+

您应该将加密数据保存到varbinary或blob列。这些数据类型没有字符集,它们只存储二进制字节。

mysql> create table tcb (company text, company_enc blob);

mysql> insert into tcb set company = 'company';

mysql> update tcb set 
    company_enc = aes_encrypt(company, '1234'),
    company = NULL; /* no more plain text copy */

mysql> select aes_decrypt(company_enc, '1234') from tcb;
+----------------------------------+
| aes_decrypt(company_enc, '1234') |
+----------------------------------+
| company                          |
+----------------------------------+

另一种解决方案是在将二进制字节转换为十六进制数字的可打印字符串后存储加密数据。

mysql> update tcb set company = 'company';

mysql> update tcb set company = hex(aes_encrypt(company, '1234'));

mysql> select company from tcb;
+----------------------------------+
| company                          |
+----------------------------------+
| 8F944F1DB907685B94F8F21554E57396 |
+----------------------------------+

mysql> select aes_decrypt(unhex(company), '1234') from tcb;
+-------------------------------------+
| aes_decrypt(unhex(company), '1234') |
+-------------------------------------+
| company                             |
+-------------------------------------+

相关问题