使用PHP Mcrypt加密并使用MySQL aes_decrypt解密? [英] Encrypt with PHP Mcrypt and Decrypt with MySQL aes_decrypt?
问题描述
是否可以使用PHP mcrypt
加密数据,并使用MySQL AES_DECRYPT
在数据库中解密数据?目前,我在PHP上将 RIJNDAEL_128
用于 mcrypt
。我还确保数据库中的加密字段的数据类型为 blob
。但是,具有正确密钥的 AES_DECRYPT
仍返回 NULL
。关于如何使它起作用的任何建议?
Is it possible to Encrypt data with PHP mcrypt
and decrypt it in the database with MySQL AES_DECRYPT
? At the moment, I'm using RIJNDAEL_128
for mcrypt
on PHP. I've also made sure that the encrypted fields in the database have data type blob
. Yet, AES_DECRYPT
with the correct key still returns NULL
. Any suggestions on how to get this to work?
推荐答案
我发现了一些很好的帮助此处
I found some good help here
请注意,此方法适用于
Note this works for encrypted text up to 65519 characters in the plain text. (maybe a bit more if no UTF-8 encoding)
要加密的PHP代码:
// MySQL uses 16 bytes key for 128 encryption/decryption
$key = "ABCDEF0123456789";
$plaintext = "This string was AES-128 / EBC / ZeroBytePadding encrypted.";
// Optionally UTF-8 encode
$plaintext_utf8 = utf8_encode($plaintext);
// Find out what's your padding
$pad_len = 16 - (strlen($plaintext_utf8) % 16);
// Padd your text
$plaintext_utf8 = str_pad($plaintext_utf8, (16 * (floor(strlen($plaintext_utf8) / 16) + 1)), chr($pad_len));
// Encryption
mt_srand();
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
mcrypt_generic_init($td, $key, false);
// Generates a warning about empty IV but it's Ok
$ciphertext = mcrypt_generic($td, $plaintext_utf8);
mcrypt_generic_deinit($td);
$ciphertext = mysql_real_escape_string($ciphertext);
// Store in MySQL
$mysqli = new mysqli("localhost", "test", "test", "test");
$mysqli->set_charset("utf8");
$mysqli->query("insert into test(content) value ('$ciphertext')");
$mysqli->close();
SQL查询以搜索字符串为
:
SQL query to search for string was
:
SELECT CAST(AES_DECRYPT(content,'ABCDEF0123456789') AS CHAR) AS content
FROM test
WHERE CAST(AES_DECRYPT(content,'ABCDEF0123456789') AS CHAR) like '%string was%';
输出为:
This string was AES-128 / EBC / ZeroBytePadding encrypted.
注意:MySQL表是由以下人员创建的:
Note: MySQL table was created by:
create table test (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
content blob ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
这篇关于使用PHP Mcrypt加密并使用MySQL aes_decrypt解密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!