PHP/JS 互通加密-解密

作者: Zero_75 | 来源:发表于2019-03-24 23:36 被阅读10次
  • 场景:服务端Php与前端Js 实现互通加密/加密
  • php7.1以后mcrypt_encrypt将被废弃,所以使用openssl_decrypt和openssl_encrypt的组合方式实现AES加密
  • 环境 PHP7.*

php加密-解密

$data = 'ABCDEFGH';
$key = "1234567898882222";
$iv = '8NONwyJtHesysWpM';
// 加密
$encode = base64_encode(openssl_encrypt($data,"AES-128-CBC",$key,true,$iv));
// 解密
$decode = openssl_decrypt(base64_decode($encode),"AES-128-CBC",$key,true,$iv);

$lists = array("encode"=>$encode,"decode"=>$decode,"iv"=>$iv,"key"=>$key,"data"=>$data);

var_dump($lists);

// 数据结果
array(5) {
  ["encode"]=>
  string(24) "uJeZ6dyWTKDMRXNOVhxRNA=="
  ["decode"]=>
  string(8) "ABCDEFGH"
  ["iv"]=>
  string(16) "8NONwyJtHesysWpM"
  ["key"]=>
  string(16) "1234567898882222"
  ["data"]=>
  string(8) "ABCDEFGH"
}

JS加密-解密

  • js端使用 CryptoJS 封装的库。
<!DOCTYPE html>
<html>
<head>
    <title>AES</title>
</head>
<script type="text/javascript" src="http://react.file.alimmdn.com/aes.js"></script>
<body>
    <script> 
        var IV = '8NONwyJtHesysWpM';
        var KEY = '1234567898882222';
        var data = 'ABCDEFGH';

        // 加密
        function encrypt(str) {
            var key = CryptoJS.enc.Utf8.parse(KEY);
            var iv = CryptoJS.enc.Utf8.parse(IV);
            var encrypted = CryptoJS.AES.encrypt(str,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7});
            return encrypted.toString();
        }

        // 解密
        function decrypt(str) {
            var key = CryptoJS.enc.Utf8.parse(KEY);
            var iv = CryptoJS.enc.Utf8.parse(IV);
            var decrypted = CryptoJS.AES.decrypt(str,key,{iv:iv,padding:CryptoJS.pad.Pkcs7});
            return decrypted.toString(CryptoJS.enc.Utf8);
        }

        var encode = encrypt(data);
        var decode = decrypt(encode);
        console.log(JSON.stringify({"encode":encode,"decode":decode,"iv":IV,"key":KEY,"data":data}));
    </script>
</body>
</html>

相关文章

网友评论

    本文标题:PHP/JS 互通加密-解密

    本文链接:https://www.haomeiwen.com/subject/prqmvqtx.html