我正在尝试使用php加密数据并插入到mysql中。加密和插入操作正常工作,但解密不会返回实际字符串。请参阅下面的加密代码
public function encryptText($text,$customer_id)
{
$key = $customer_id;
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB);
return $crypttext;
}
用于解密
public function decryptText($ctext,$customer_id)
{
$key = $customer_id;
$text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,$key,$ctext,MCRYPT_MODE_ECB);
return $text;
}
请帮助我解决这个问题
最有可能的问题是您没有使用正确的密钥来解密加密的数据。您的代码显示了许多问题真的查看:
- 密钥最好是一个二进制字符串。
$customer_id
的具体内容是什么?即使这是一个字符串,它也应该是128、192或256位长。它看起来不像是 - 即使密钥在技术上是可以接受的,使用客户id作为密钥也根本不能提供任何安全性
MCRYPT_RIJNDAEL_256
中的256不指定加密强度,而是指定块大小。在几乎所有情况下,都应该使用MCRYPT_RIJNDAEL_128
——事实上,这样做与AES相同。MCRYPT_RIJNDAEL_256
不是AES
这些函数将接受任何PHP对象并对其进行加密/解密:
加密JSON对象Rijndael ECB base 64编码
function ejor2eb($object, $key) {
// Encode the object
$object = json_encode($object, JSON_FORCE_OBJECT);
// Add length onto the encoded object so we can remove the excess padding added by AES
$object = strlen($object) . ':' . $object;
// Encrypt the string
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
$result = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $object, MCRYPT_MODE_ECB, $iv);
// Return the URL encoded string, with the encryption type attached
return 'jor2eu:' . base64_encode($result);
}
解密JSON对象Rijndael ECB base64解码
function djor2eb($string, $key, $default = false) {
// Remove the encryption type, and decode the string
$binary = base64_decode(substr($string, 7));
if (!$binary) {
return $default;
}
// Decrypt the string
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
$result = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $binary, MCRYPT_MODE_ECB, $iv);
// Remove encrption padding
$tokens = null;
preg_match('/^([0-9]+):/i', $result, $tokens);
if (sizeof($tokens) !== 2) {
return $default;
}
$result = substr($result, strlen($tokens[1]) + 1, $tokens[1]);
// Decode the ecoded object
$object = json_decode($result);
return $object;
}