<?php
function secureEncrypt($plaintext, $key) {
$iv = random_bytes(16);
$ciphertext = openssl_encrypt(
$plaintext,
'aes-256-ctr',
hash('sha256', $key, true),
OPENSSL_RAW_DATA,
$iv
);
return base64_encode($iv . hash_hmac('sha3-256', $ciphertext, $key, true) . $ciphertext);
}
function secureDecrypt($ciphertext, $key) {
$data = base64_decode($ciphertext);
$iv = substr($data, 0, 16);
$hmac = substr($data, 16, 32);
$content = substr($data, 48);
if (!hash_equals(hash_hmac('sha3-256', $content, $key, true), $hmac)) {
throw new Exception('完整性验证失败');
}
return openssl_decrypt(
$content,
'aes-256-ctr',
hash('sha256', $key, true),
OPENSSL_RAW_DATA,
$iv
);
}
$masterKey = random_bytes(32);
$data = "绝密信息123";
$encrypted = secureEncrypt($data, $masterKey);
try {
echo secureDecrypt($encrypted, $masterKey);
} catch(Exception $e) {
die("解密失败: ".$e->getMessage());
}