<?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());
}
function secureCrypt($data, $password, $isEncrypt = true) {
$method = 'aes-256-ctr';
$key = hash('sha256', $password, true);
if ($isEncrypt) {
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $iv . $ciphertext, $key, true);
return base64_encode($iv . $hmac . $ciphertext);
} else {
$raw = base64_decode($data);
if (strlen($raw) < 48) return false;
$iv = substr($raw, 0, 16);
$hmac = substr($raw, 16, 32);
$ciphertext = substr($raw, 48);
$calculatedHmac = hash_hmac('sha256', $iv . $ciphertext, $key, true);
if (!hash_equals($hmac, $calculatedHmac)) return false;
return openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
}
}
$secretData = "交易凭证2025-001";
$encrypted = secureCrypt($secretData, getenv('ENCRYPTION_KEY'));
$decrypted = secureCrypt($encrypted, getenv('ENCRYPTION_KEY'), false);
if ($decrypted === false) {
error_log("解密失败:可能遭遇数据篡改");
} else {
echo "解密成功:".$decrypted;
}