Search K
Appearance
👇公众号👇---👇 微信 👇
有缘人请我喝杯咖啡吧
👇 微信 👇---👇支付宝👇
Appearance
TIP
php是一种开源的服务器端编程语言,广泛应用于web开发领域。由于web应用程序中经常涉及到用户的敏感信息,如密码、银行卡号等,因此对这些信息进行加密和解密保护就显得尤为重要。 本文将介绍在PHP中如何使用openssl扩展库可以对数据进行AES加密和解密
extension_loaded('openssl') or die('PHP加密需要openssl扩展支持');
<?php
namespace application\service\Encrypt;
class OpenSslEncrypt
{
private $key;//AES密钥:32位
private $iv;//随机IV
public function __construct()
{
$encryptKey = "a*a~W(eUuY/?^Ps*";
$this->iv = md5($encryptKey);
$this->key = hash('sha256', $this->iv, true);
}
public function encrypt($input)
{
$data = openssl_encrypt($input, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->iv));
return base64_encode($data);
}
public function decrypt($input)
{
return openssl_decrypt(base64_decode($input), 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->iv));
}
function hexToStr($hex)
{
$string = '';
for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
$string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
}
return $string;
}
}
?>
<?php
$openSslEncrypt = new OpenSslEncrypt();
// 加密
$encryptData = $openSslEncrypt->encrypt("Hello word !");//输出:YU8sHAfCxDHt7XUV7h7dmw==
//解密
$decryptData = $openSslEncrypt->decrypt($encryptData);//输出:Hello word !