在 MySQL 中加密和解密字符串?
mysqlmysqli database
要在 MySQL 中加密和解密,请使用 MySQL 中的 AES_ENCRYPT() 和 AES_DECRYPT() −
insert into yourTableName values(AES_ENCRYPT(yourValue,yourSecretKey)); select cast(AES_DECRYPT(yourColumnName, yourSecretKey) as char) from yourTableName;
为了理解上述语法,让我们首先创建一个表 −
mysql> create table demo63 −> ( −> value blob −> ); Query OK, 0 rows affected (2.60 sec)
使用 insert 命令向表中插入一些记录。我们在插入时进行加密 −
mysql> insert into demo63 values(AES_ENCRYPT('John','PASS')); Query OK, 1 row affected (0.18 sec) mysql> insert into demo63 values(AES_ENCRYPT('David','PASS')); Query OK, 1 row affected (0.41 sec) mysql> insert into demo63 values(AES_ENCRYPT('123456','PASS')); Query OK, 1 row affected (0.41 sec)
使用 select 语句显示表中的记录 −
mysql> select *from demo63;
这将产生以下输出 −
+------------------------------------+ | value | +------------------------------------+ | 0x16D8A4F11321D761920783BF96BB8314 | | 0x0A85099F705F21D27B0129C54C4473AA | | 0xAB7C6D6068BC100B0F04D1C4EA068AC9 | +------------------------------------+ 3 rows in set (0.00 sec)
以下是解密查询 −
mysql> select cast(aes_decrypt(value, 'PASS') AS char) from demo63;
这将产生以下输出 −
+------------------------------------------+ | cast(aes_decrypt(value, 'PASS') AS char) | +------------------------------------------+ | John | | David | | 123456 | +------------------------------------------+ 3 rows in set (0.00 sec)