這些功能將採取任何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基地64解碼
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;
}
*「正常工作,但解密不會返回實際的字符串」* - Sooo,它*不*工作正常呢? ; P – deceze
通常用db來加密數據,如果壞人有權訪問數據庫,他們可能有權訪問用於加密數據的代碼。 – 2012-09-06 10:40:54
你可以發佈你的「測試」代碼嗎?因爲你的代碼的工作原理應該如此。我想,有一些問題,字符串填充或$ customer_id(鍵)參數鑄造。 – Salaros