转载地址 https://segmentfault.com/a/1190000010128665
php加密解密类
<?php
/*
+--------------------------------------------------------------------------
| 由于在php7.1之后mcrypt_encrypt会被废弃,因此使用openssl_encrypt方法来替换
| ========================================
| by Focus
| ========================================
|
|
+---------------------------------------------------------------------------
*/
class OpensslEncryptHelper
{
/**向量
* @var string
*/
const IV = "1234567890123412";//16位
/**
* 默认秘钥
*/
const KEY = '201707eggplant99';//16位
/**
* 解密字符串
* @param string $data 字符串
* @param string $key 加密key
* @return string
*/
public static function decryptWithOpenssl($data,$key = self::KEY,$iv = self::IV){
return openssl_decrypt(base64_decode($data),"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv);
}
/**
* 加密字符串
* 参考网站: https://segmentfault.com/q/1010000009624263
* @param string $data 字符串
* @param string $key 加密key
* @return string
*/
public static function encryptWithOpenssl($data,$key = self::KEY,$iv = self::IV){
// echo base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, "1234567890123456", pkcs7_pad("123456"), MCRYPT_MODE_CBC, "1234567890123456"));
// echo base64_encode(openssl_encrypt("123456","AES-128-CBC","1234567890123456",OPENSSL_RAW_DATA,"1234567890123456"));
// $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, self::$iv);
// return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, "1234567890123456", pkcs7_pad("123456"), MCRYPT_MODE_CBC, "1234567890123456"));
return base64_encode(openssl_encrypt($data,"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv));
}
}
js端的关键代码
扫码123APP项目使用
自定义封装的crypto-helper-pkcs7.js
var IV = '1234567890123412';
var KEY = '201707eggplant99'
/**
* 加密
*/
function encrypt(str) {
key = CryptoJS.enc.Utf8.parse(KEY);// 秘钥
var iv= CryptoJS.enc.Utf8.parse(IV);//向量iv
var encrypted = CryptoJS.AES.encrypt(str, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
return encrypted.toString();
}
/**
* 解密
* @param str
*/
function decrypt(str) {
var key = CryptoJS.enc.Utf8.parse(KEY);// 秘钥
var iv= CryptoJS.enc.Utf8.parse(IV);//向量iv
var decrypted = CryptoJS.AES.decrypt(str,key,{iv:iv,padding:CryptoJS.pad.Pkcs7});
return decrypted.toString(CryptoJS.enc.Utf8);
}
test_crypto_pcks7.html代码
<html>
<head>test crypto-js</head>
<script src="crypto-js/aes.js" type="text/javascript"></script>
<script src="crypto-js/md5.js" type="text/javascript"></script>
<script src="crypto-js/cryptoJS.min.js" type="text/javascript" charset="utf-8"></script>
<script src="crypto-helper-pkcs7.js" type="text/javascript"></script>
<script type="text/javascript">
var data = '111111';
var encode = encrypt(data);
console.log('encode is =======>'+encode);
var decode = decrypt(encode);
console.log('decode is =======>'+decode);
alert('encode is ====>'+encode+',decode is ====>'+decode);
</script>
</html>