本文共 1910 字,大约阅读时间需要 6 分钟。
本文介绍了一个基于PHP的AES-256-CBC加密实现,该实现采用OpenSSL库进行加密和解密操作。整个过程以安全性和兼容性为核心设计理念,确保数据传输和存储的完整性和安全性。
本实现采用AES-256-CBC模式进行加密。CBC模式具有以下优势:
密钥生成采用SHA256哈希算法。通过对用户提供的密码($password)进行SHA256计算,生成256位的密钥。这种方法确保了密钥的唯一性和安全性。
为确保数据未被篡改,实现中引入了哈希值(HMAC)的验证机制。具体流程如下:
function encrypt($plaintext, $password) { $method = "AES-256-CBC"; $key = hash('sha256', $password, true); $iv = openssl_random_pseudo_bytes(16); $ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv); $hash = hash_hmac('sha256', $ciphertext, $key, true); return $iv . $hash . $ciphertext;} 加密后的数据由以下部分组成,按顺序排列:
function decrypt($ivHashCiphertext, $password) { $method = "AES-256-CBC"; $iv = substr($ivHashCiphertext, 0, 16); $hash = substr($ivHashCiphertext, 16, 32); $ciphertext = substr($ivHashCiphertext, 48); $key = hash('sha256', $password, true); if (hash_hmac('sha256', $ciphertext, $key, true) !== $hash) { return null; } return openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);} 解密成功时,返回原始明文;失败时,返回null。
$encrypted = encrypt('Plaintext string.', 'password');echo decrypt($encrypted, 'password'); // 输出明文 通过以上实现,您可以轻松在PHP环境中实现安全的数据加密和解密功能,同时确保数据的完整性和一致性。
转载地址:http://ihvfk.baihongyu.com/