对于项目需求,我需要在mysql中以加密格式存储值。在PHP和Mysql中,解密和加密都是可能的。我试过使用openssl加密解密。在mysql版本小于5.7的情况下,我们不能设置加密模式。默认模式是aes-128-ecb.当我试图在openssl中使用相同的模式解密时,我会得到null。
查询:从AES_ENCRYPT中选择tbl_name(‘ABCD’,‘69f0ff56314d4e2d2d2bc89f6f4b5292c’);
结果: 0x907fb5ce60223d205e7c0f0bc338d563
当我将这个结果传递给PHP时:
<?php
$plaintext = "0x907fb5ce60223d205e7c0f0bc338d563";
$cipher = "aes-128-ecb";
$key = "69f0ff56314d4e2d02bc89f6f4b5292c";
if(in_array($cipher, openssl_get_cipher_methods())) {
$ciphertext = openssl_decrypt($plaintext, $cipher, $key);
echo $ciphertext;
}它不起作用。你知道我错过了什么吗?还有其他方法来实现它吗?Mysql版本: 5.0 PHP :7
发布于 2020-10-23 10:41:27
PHP代码中存在一些问题,但最重要的是通过MySQL文档中没有命名的函数从给定密钥中“派生”解密密钥。
我从这个网站和获得了信息和功能,所有的信用都归他们所有,:https://www.smashingmagazine.com/2012/05/replicating-mysql-aes-encryption-methods-with-php/。
其他问题是: a)密文是二进制表示的十六进制编码字符串;b) openssl_decrypt函数末尾的"true“参数将数据作为二进制而不是Base64编码。
安全警告:此代码使用的是不安全的AES模式'EBC',这是一个静态密钥,处理没有任何异常。该代码仅用于教育目的。
这是一个简单的、预期的输出--您可以通过我的在线编译器(https://repl.it/@javacrypto/PhpAesDecryptFromMysql)运行代码:
ABCD完整运行的源代码:
<?php
function mysql_aes_key($key)
// source: https://www.smashingmagazine.com/2012/05/replicating-mysql-aes-encryption-methods-with-php/
{
$new_key = str_repeat(chr(0), 16);
for ($i = 0, $len = strlen($key); $i < $len; $i++) {
$new_key[$i % 16] = $new_key[$i % 16] ^ $key[$i];
}
return $new_key;
}
$ciphertextFromMysql = "907fb5ce60223d205e7c0f0bc338d563";
$key = "69f0ff56314d4e2d02bc89f6f4b5292c";
$ciphertext = hex2bin($ciphertextFromMysql);
$cipher = "aes-128-ecb";
if (in_array($cipher, openssl_get_cipher_methods())) {
//$ciphertext = openssl_decrypt($ciphertext, $cipher, $key, true);
$decrypttext = openssl_decrypt($ciphertext, $cipher, mysql_aes_key($key), true);
echo $decrypttext;
}
?>https://stackoverflow.com/questions/64497414
复制相似问题