對稱密碼
此示例說明了 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);