PHP 中的 AES-256 加密
2022-08-30 16:07:42
我需要一个PHP函数,将加密成AES-256,另一个函数则相反。有谁知道这个函数应该有什么代码?AES256_encode($dataToEcrypt)
$data
AES256_decode($encryptedData)
我需要一个PHP函数,将加密成AES-256,另一个函数则相反。有谁知道这个函数应该有什么代码?AES256_encode($dataToEcrypt)
$data
AES256_decode($encryptedData)
查看 mcrypt 模块
AES-Rijndael示例取自此处
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
# show key size use either 16, 24 or 32 byte keys for AES-128, 192
# and 256 respectively
$key_size = strlen($key);
echo "Key size: " . $key_size . "\n";
$text = "Meet me at 11 o'clock behind the monument.";
echo strlen($text) . "\n";
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv);
echo strlen($crypttext) . "\n";
这是解密功能
我需要一个PHP函数,将加密成AES-256,另一个函数则相反。有谁知道这个函数应该有什么代码?
AES256_encode($dataToEcrypt)
$data
AES256_decode($encryptedData)
你真的需要AES-256吗?AES-256与AES-128的安全性并不那么重要。你更有可能在协议层搞砸,而不是被黑客入侵,因为你使用了128位块密码而不是256位块密码。
如果您有兴趣构建自己的产品,不是为了在生产环境中部署它,而是为了您自己的教育,那么我提供了一个示例AES256
/**
* This is a quick and dirty proof of concept for StackOverflow.
*
* @ref http://stackoverflow.com/q/6770370/2224584
*
* Do not use this in production.
*/
abstract class ExperimentalAES256DoNotActuallyUse
{
/**
* Encrypt with AES-256-CTR + HMAC-SHA-512
*
* @param string $plaintext Your message
* @param string $encryptionKey Key for encryption
* @param string $macKey Key for calculating the MAC
* @return string
*/
public static function encrypt($plaintext, $encryptionKey, $macKey)
{
$nonce = random_bytes(16);
$ciphertext = openssl_encrypt(
$plaintext,
'aes-256-ctr',
$encryptionKey,
OPENSSL_RAW_DATA,
$nonce
);
$mac = hash_hmac('sha512', $nonce.$ciphertext, $macKey, true);
return base64_encode($mac.$nonce.$ciphertext);
}
/**
* Verify HMAC-SHA-512 then decrypt AES-256-CTR
*
* @param string $message Encrypted message
* @param string $encryptionKey Key for encryption
* @param string $macKey Key for calculating the MAC
*/
public static function decrypt($message, $encryptionKey, $macKey)
{
$decoded = base64_decode($message);
$mac = mb_substr($message, 0, 64, '8bit');
$nonce = mb_substr($message, 64, 16, '8bit');
$ciphertext = mb_substr($message, 80, null, '8bit');
$calc = hash_hmac('sha512', $nonce.$ciphertext, $macKey, true);
if (!hash_equals($calc, $mac)) {
throw new Exception('Invalid MAC');
}
return openssl_decrypt(
$ciphertext,
'aes-256-ctr',
$encryptionKey,
OPENSSL_RAW_DATA,
$nonce
);
}
}
首先,生成两个密钥(是的,其中两个)并以某种方式存储它们。
$eKey = random_bytes(32);
$aKey = random_bytes(32);
然后加密/解密消息:
$plaintext = 'This is just a test message.';
$encrypted = ExperimentalAES256DoNotActuallyUse::encrypt($plaintext, $eKey, $aKey);
$decrypted = ExperimentalAES256DoNotActuallyUse::decrypt($encrypted, $eKey, $aKey);
如果没有,请random_compat。random_bytes()