<?php
// 使用PHP内置的加密函数进行简单加密和解密示例
// 定义一个密钥,用于加密和解密
$secret_key = 'my_secret_key';
// 要加密的字符串
$data_to_encrypt = 'Hello, this is a secret message!';
// 加密函数
function encrypt($data, $key) {
// 使用openssl_encrypt函数进行加密
// 方法: AES-128-CBC
// 注意: 需要生成一个合适的初始化向量 (IV)
$method = 'AES-128-CBC';
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);
// 加密数据并返回加密后的数据和IV(IV需要保存以便解密时使用)
$encrypted_data = openssl_encrypt($data, $method, $key, 0, $iv);
return base64_encode($iv . $encrypted_data);
}
// 解密函数
function decrypt($data, $key) {
// 使用openssl_decrypt函数进行解密
$method = 'AES-128-CBC';
$data = base64_decode($data);
$iv_length = openssl_cipher_iv_length($method);
$iv = substr($data, 0, $iv_length);
$encrypted_data = substr($data, $iv_length);
// 解密数据并返回原始数据
return openssl_decrypt($encrypted_data, $method, $key, 0, $iv);
}
// 加密示例
$encrypted_data = encrypt($data_to_encrypt, $secret_key);
echo "Encrypted Data: " . $encrypted_data . "\n";
// 解密示例
$decrypted_data = decrypt($encrypted_data, $secret_key);
echo "Decrypted Data: " . $decrypted_data . "\n";
?>
openssl_encrypt 函数对数据进行加密。加密方法为 AES-128-CBC,并且生成了一个初始化向量 (IV)。加密后的数据和IV一起被编码为Base64格式返回。openssl_decrypt 函数对数据进行解密。首先解码Base64格式的数据,提取出IV,然后使用IV和密钥解密数据。希望这段代码对你有帮助!
上一篇:php 连接数据库
下一篇:php 加密解密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站