类1:
<?php // error_reporting(E_ALL || ~E_NOTICE); class Encrypt { /** * var string $method 加解密方法,可通过openssl_get_cipher_methods()获得 */ private $method; /** * var string $secret_key 加解密的密钥 */ private $key; /** * var string $iv 加解密的向量,有些方法需要设置比如CBC */ private $iv; /** * var string $options (不知道怎么解释,目前设置为0没什么问题) */ private $options; /** * 构造函数 * * @param string $key 密钥 * @param string $method 加密方式 * @param mixed $options openssl_簇 * @param string $iv iv向量 * */ public function __construct($key = 'vxfw2hvftmna6ux3', $method = 'AES-128-ECB', $options = 0, $iv = 'tmna') { $this->key = $key; $this->method = $method; $this->options = $options; $this->iv = $iv; } /** * 加密方法,对数据进行加密,返回加密后的数据 * * @param string $data 要加密的数据 * @return string */ public function encrypt($data) { return openssl_encrypt($data, $this->method, $this->key, $this->options); } /** * 解密方法,对数据进行解密,返回解密后的数据 * * @param string $data 要解密的数据 * @return string */ public function decrypt($data) { return openssl_decrypt($data, $this->method, $this->key, $this->options); } }
类2:
<?php class ApUtilOpensslCrypt { //密匙 var $key = NULL; var $algorithm = NULL; var $mode = NULL; function __construct($key = "vxfw2hvf") { //初始化密匙 $this->key = ($key != "") ? $key : ""; //加密算法 $this->algorithm = 'AES-128-ECB'; //加密模式 $this->mode = OPENSSL_RAW_DATA; } /** * * @param string $data 需要加密的字符串 * @return string */ public function encrypt($data) { return openssl_encrypt($data,$this->algorithm,$this->key); $data = $this->base64_url_encode(openssl_encrypt($data,$this->algorithm,$this->key)); return $data; } /** * @param string $data 需要解密的字符串 * @return string */ public function decrypt($data) { return openssl_decrypt($this->base64_url_decode($data), $this->algorithm, $this->key, $this->mode); $decrypted = openssl_decrypt($this->base64_url_decode($data), $this->algorithm, $this->key, $this->mode); return $decrypted; } public function base64_url_encode($input) { return strtr($input, '+/=', '-_,'); } public function base64_url_decode($input) { return base64_decode(strtr($input, '-_,', '+/=')); } }
用法:
$en_two_str = "Ed3MFQFVRRgO4Rz+hZVwtQ=="; //如果类在外部(没和用法在同一个文件里面),需要先引入类 // $aaa = new Encrypt(); // echo "加密前:".$str."\n"; // $en_str = $aaa->encrypt($str); // echo "加密后:".$en_str."\n"; // echo "解密后:".$aaa->decrypt($en_str)."\n"; // echo "------------------------------"."\n"; $bbb = new ApUtilOpensslCrypt(); // echo "加密前:".$str."\n"; // $en_two_str = $bbb->encrypt($str); // echo "加密后:".$en_two_str."\n"; echo "解密后:".$bbb->decrypt($en_two_str);