教程集 www.jiaochengji.com
教程集 >  数据库  >  mysql  >  正文 mysql加密函数aes_encrypt()和aes_decrypt()使用教程

mysql加密函数aes_encrypt()和aes_decrypt()使用教程

发布时间:2017-12-11   编辑:jiaochengji.com
教程集为您提供mysql加密函数aes,encrypt()和aes,decrypt()使用教程等资源,欢迎您收藏本站,我们将为您提供最新的mysql加密函数aes,encrypt()和aes,decrypt()使用教程资源
aes_encrypt()和aes_decrypt()在mysql中是进行加密了,我们今天一起来和各位看看关于mysql中aes_encrypt()和aes_decrypt()函数的使用例子.

如果你需要对mysql某些字段进行加解密的话,使用mysql的加解密函数可能比程序中处理更方便.
mysql-encrypt-funcs.png以aes_encrypt()和aes_decrypt()为例

mysql-encrypt-funcs.png

特别需要注意的时mysql5.5及以下的版本仅支持aes-128-ecb模式,如果需要其它模式需要mysql5.6及以上版本才支持,可通过mysql全局变量如下方式指定:

mysql> SET block_encryption_mode = 'aes-256-cbc';
mysql> SET @key_str = SHA2('My secret passphrase',512);
mysql> SET @init_vector = RANDOM_BYTES(16);
mysql> SET @crypt_str = AES_ENCRYPT('text',@key_str,@init_vector);
mysql> SELECT AES_DECRYPT(@crypt_str,@key_str,@init_vector);
-----------------------------------------------
| AES_DECRYPT(@crypt_str,@key_str,@init_vector) |
-----------------------------------------------
| text                                          |
-----------------------------------------------

参考文档如下:

https://dev.mysql.com/doc/refman/5.5/en/encryption-functions.html#function_aes-encrypt
http://dev.mysql.com/doc/refman/5.7/en/encryption-functions.html#function_aes-encrypt

关于加密的二进制数据在mysql中字段存什么类型(存blob还是varbinay类型)?
引用文档一段话:

Many encryption and compression functions return strings for which the result might contain arbitrary byte values. If you want to store these results, use a column with a VARBINARY or BLOB binary string data type. This will avoid potential problems with trailing space removal or character set conversion that would change data values, such as may occur if you use a nonbinary string data type (CHAR, VARCHAR, TEXT).

尽量使用blob类型,原因如下:

There is no trailing-space removal for BLOB columns when values are stored or retrieved.
For indexes on BLOB columns, you must specify an index prefix length.
BLOB columns can not have DEFAULT values.

二进制数据如何使用sql插入?

不可直接拼接sql插入,否则会被当成字符串处理,不可你可以将二进制数据转换程十六进制或base64插入,相应的,取出来的时候你也需要转换。但是通过mysql prepared statement方式可以插入stream data,如php pdo可以类似如下实现:

$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // some function to allocate a new ID
 
// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation
 
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
 
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);
 
$db->beginTransaction();
$stmt->execute();
$db->commit();

 

您可能感兴趣的文章:
mysql加密与解密函数的用法
mysql加密函数aes_encrypt()和aes_decrypt()使用教程
mysql函数大全(3)
学习mysql root密码修改的方法及工具使用
破解mysql root密码的几种方法
mysql修改密码的六种方法
php base64加密解密的实现代码
PHP如何使用AES加密和解密
【哈希密码】PHP比md5更安全的加密方式
MySQL数据库安全解决方案

[关闭]
~ ~