编辑代码

<?php 


function secureEncrypt($plaintext, $key) {
    $iv = random_bytes(16); // 生成强随机IV‌:ml-citation{ref="5,7" data="citationList"}
    $ciphertext = openssl_encrypt(
        $plaintext, 
        'aes-256-ctr', // 选择CTR模式提升性能‌:ml-citation{ref="5" data="citationList"}
        hash('sha256', $key, true), // 密钥哈希处理‌:ml-citation{ref="1,5" data="citationList"}
        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('完整性验证失败'); // HMAC防篡改‌:ml-citation{ref="5,8" data="citationList"}
    }
    
    return openssl_decrypt(
        $content,
        'aes-256-ctr',
        hash('sha256', $key, true),
        OPENSSL_RAW_DATA,
        $iv
    );
}



$masterKey = random_bytes(32); // 必须使用密码学安全随机数‌:ml-citation{ref="5" data="citationList"}
$data = "绝密信息123";

// 加密
$encrypted = secureEncrypt($data, $masterKey);

// 解密
try {
    echo secureDecrypt($encrypted, $masterKey);
} catch(Exception $e) {
    die("解密失败: ".$e->getMessage());
}