主要应用在传输密码上有两种方法
第一种较为复杂
<?php
namespace Aes;
class Aes
{
/**
* var string $method 加解密方法,可通过openssl_get_cipher_methods()获得
*/
protected $method;
/**
* var string $secret_key 加解密的密钥
*/
protected $secret_key;
/**
* var string $iv 加解密的向量,有些方法需要设置比如CBC
*/
protected $iv;
/**
* var string $options (不知道怎么解释,目前设置为0没什么问题)
*/
protected $options;
/**
* 构造函数
*
* @param string $key 密钥
* @param string $method 加密方式
* @param string $iv iv向量
* @param mixed $options 还不是很清楚
*
*/
public function __construct($key, $method = 'AES-128-ECB', $iv = '', $options = 0)
{
// key是必须要设置的
$this->secret_key = isset($key) ? $key : 'morefun';
$this->method = $method; // 密码算法
$this->iv = $iv;
$this->options = $options;
}
/**
* 加密方法,对数据进行加密,返回加密后的数据
*
* @param string $data 要加密的数据
*
* @return string
*
*/
public function encrypt($data)
{
return openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
}
/**
* 解密方法,对数据进行解密,返回解密后的数据
*
* @param string $data 要解密的数据
*
* @return string
*
*/
public function decrypt($data)
{
return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
}
}
$data = 'AarthiModoo';
$aes = new Aes('002c7a70ee0a11e89ab2335952b4125e'); // 实例化类
$encrypted = $aes->encrypt($data); // 加密
echo "要加密的字符串:$data<br>加密后的字符串:", $encrypted, '<hr>';
$decrypted = $aes->decrypt($encrypted); // 解密
echo '要解密的字符串:', $encrypted, '<br>解密后的字符串:', $decrypted;
第二种简单,可以兼容前端
<?php
header('Content-Type: text/html; charset=utf-8'); //网页编码
/*
* 加密
* */
function encode($cryptkey, $iv, $secretdata){
return openssl_encrypt($secretdata,'aes-256-cbc',$cryptkey,false,$iv);
}
/*
* 解密
* */
function decode($cryptkey, $iv, $secretdata){
return openssl_decrypt($secretdata,'aes-256-cbc',$cryptkey,false,$iv);
}
$cryptkey = hash('sha256','杨云昊',false);
$iv = '1234567890000000';
$buf = "Hello World";
echo encode($cryptkey,$iv,$buf).'<br/>';
echo decode($cryptkey,$iv,encode($cryptkey,$iv,$buf));