所以我只是在我的
mysql表上做一些基本的数据加密.我遵循了这里的指导方针
https://dev.mysql.com/doc/refman/5.6/en/encryption-functions.html#function_aes-encrypt
https://dev.mysql.com/doc/refman/5.6/en/encryption-functions.html#function_aes-encrypt
但我遇到了一个问题.虽然我知道我可以在my@R_301_194@中使用aes_decrypt来解密数据.我想也有能力让PHP自己这样做.
我已经让这部分工作了.如果MysqL像这样执行非常基本的AES_ENCRYPTION
INSERT INTO tablename (dataset) VALUES (AES_ENCRYPT('testvalue','mysecretphrase'))
我能用这样的解密来解决这个问题
openssl_decrypt(base64_encode($dR['dataset']),'aes-128-ecb','mysecretphrase')
当我使用MysqL在上面的URL中提到的推荐的UNHEX(SHA2(‘mysecretphrase’,512))时,我的问题出现了.
我尝试使用的PHP sha *函数可以确认它们都生成与MysqLs sha2()相同的字符串
openssl_digest('mysecretphrase','sha512') // AND hash('sha512','mysecretphrase')
最后解决MysqL使用的UNHEX(),经过一些研究后我发现PHP hex2bin == unhex http://www.php.net/manual/en/function.hex2bin.php
但是,我在解密数据时没有得到任何结果.这是它一直失败的地方.我觉得好像我要么缺少一些东西,但这只是不解密数据而只返回空结果.
openssl_decrypt(base64_encode($dR['dataset']),hex2bin(openssl_digest('mysecretphrase','sha512')))
任何帮助,指针或提示将不胜感激.
openssl_encrypt()和openssl_decrypt()静默将密钥切割为最大16字节长度(至少对于aes-128-ecb)
<?PHP $key1 = hex2bin(openssl_digest('mysecretphrase','sha512')); $key2 = substr($key1,16); $key3 = substr($key1,15); $method = 'aes-128-ecb'; $in = 'testvalue'; $data1 = base64_decode(openssl_encrypt($in,$method,$key1)); $data2 = base64_decode(openssl_encrypt($in,$key2)); $data3 = base64_decode(openssl_encrypt($in,$key3)); var_dump( array( 'key1'=>bin2hex($key1),'key2'=>bin2hex($key2),'key3'=>bin2hex($key3),'data1'=>bin2hex($data1),'data2'=>bin2hex($data2),'data3'=>bin2hex($data3),'data1==data2'=>($data1===$data2),'data1==data3'=>($data1===$data3) ) ); ?>
结果:
array(8) { ["key1"]=>string(128) "5fe76dfd5b75cf7cf68fae85d26fcc9b7951806ad6daaa71d843c6ec0e0ec9233a828ad9b60986a43d734983c8a0a50d3a0a49ec5ac196cfcc136aa16e0c5f89" ["key2"]=>string(32) "5fe76dfd5b75cf7cf68fae85d26fcc9b" ["key3"]=>string(30) "5fe76dfd5b75cf7cf68fae85d26fcc" ["data1"]=>string(32) "eb69e89312c1f7b9522d0e66346f2029" ["data2"]=>string(32) "eb69e89312c1f7b9522d0e66346f2029" ["data3"]=>string(32) "664f5a28d241f959beac350f2314b079" ["data1==data2"]=>bool(true) ["data1==data3"]=>bool(false) }
在MysqL中,AES_ENCRYPT()和AES_DECRYPT()使用全长密钥
SELECT HEX(AES_ENCRYPT('testvalue',UNHEX(SHA2('mysecretphrase',512)))) AS l_full,HEX(AES_ENCRYPT('testvalue',SUBSTR(UNHEX(SHA2('mysecretphrase',512)),1,16))) AS l_16,15))) AS l_15;
结果:
l_full | l_16 | l_15 ---------------------------------|----------------------------------|---------------------------------------- A88DD1EFB377FD31A0EFA55EA29BA8C6 | EB69E89312C1F7B9522D0E66346F2029 | 664F5A28D241F959BEAC350F2314B079