对称密码
此示例说明了 CBC 模式下的 AES 256 对称密码。需要初始化向量,因此我们使用 openssl 函数生成一个。变量 $strong
用于确定生成的 IV 是否加密强。
加密
$method = "aes-256-cbc"; // cipher method
$iv_length = openssl_cipher_iv_length($method); // obtain required IV length
$strong = false; // set to false for next line
$iv = openssl_random_pseudo_bytes($iv_length, $strong); // generate initialization vector
/* NOTE: The IV needs to be retrieved later, so store it in a database.
However, do not reuse the same IV to encrypt the data again. */
if(!$strong) { // throw exception if the IV is not cryptographically strong
throw new Exception("IV not cryptographically strong!");
}
$data = "This is a message to be secured."; // Our secret message
$pass = "Stack0verfl0w"; // Our password
/* NOTE: Password should be submitted through POST over an HTTPS session.
Here, it's being stored in a variable for demonstration purposes. */
$enc_data = openssl_encrypt($data, $method, $password, true, $iv); // Encrypt
解密
/* Retrieve the IV from the database and the password from a POST request */
$dec_data = openssl_decrypt($enc_data, $method, $pass, true, $iv); // Decrypt
Base64 编码和解码
如果需要以可打印文本发送或存储加密数据,则应分别使用 base64_encode()
和 base64_decode()
函数。
/* Base64 Encoded Encryption */
$enc_data = base64_encode(openssl_encrypt($data, $method, $password, true, $iv));
/* Decode and Decrypt */
$dec_data = openssl_decrypt(base64_decode($enc_data), $method, $password, true, $iv);