我需要一个 PHP 函数 AES256_encode($dataToEcrypt) 将 $data 加密为 AES-256,而另一个 AES256_decode($encryptedData) 则相反。有谁知道这个函数应该有什么代码?
有一个difference between encrypting and encoding。
您真的需要 AES-256 吗? AES-256 与 AES-128 的安全性并不重要。你更有可能在协议层搞砸而不是被黑客入侵,因为你使用的是 128 位分组密码而不是 256 位分组密码。
重要 - 使用库
快速而肮脏的 AES-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_bytes(),请获取random_compat。