PHP 基于openssl 的 AES 加密与解密

PHP 7以后不再支持 mcrypt 模块,采用openssl进行替换。下述代码实现了对文本的128位 AES-ECB加密算法。
通过substr(openssl_digest(openssl_digest($this->secret_key, ‘sha1’, true), ‘sha1’, true), 0, 16)函数,实现了等价于JAVA 端加密时使用的SHA1PRNG,根据用户提供的密码,生成128位密钥。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AES加密测试</title>
</head>
<body>
<?php
	
class AES{
   
    protected $method;//加密算法
    protected $secret_key;//密钥

    public function __construct(){}//类构建函数

    /**
     * AES加密算法
	 *
     * @param string $content  加密内容
	 * 
	 * @param string $password 密钥
	 
     * @return string
     */
    public function encrypt($content,$password)
    {
		if (!isset($content)||$content=='') {
			return '';
		}
		$this->secret_key = isset($password) ? $password : exit('');//判断是否输入密钥
		$this->method = 'AES-128-ECB';//定义AES加密算法
		$this->secret_key = substr(openssl_digest(openssl_digest($this->secret_key, 'sha1', true), 'sha1', true), 0, 16);	//根据输入的password,基于sha1哈希加密给定的密码,保留16字节	
		$result = openssl_encrypt($content, $this->method, $this->secret_key);//加密
		$str = base64_encode($result);		
        return $str;//返回结果
    }
	/**
     * AES解密算法
	 *
     * @param string $content  密文	 
	 *
     * @return string
     */
    public function decrypt($content)
    {
		$content = base64_decode($content);
        return openssl_decrypt($content, $this->method, $this->secret_key);
    }		
}	


	
$content = "幸福每一天";
$password = '12345678abcdefgh';
$security = new AES();
$value = $security->encrypt($content,$password);
echo "==================原文==================<br/>";
echo $content.'<br/>';
echo "==================加密==================<br/>";
echo $value.'<br/>';
echo "==================解密==================<br/>";
echo $security->decrypt($value).'<br/>';
//var_dump($security->sign($content)).'<br/>';
?>
</body>
</html>

测试结果
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值