Laravel开发实践程序员php技术

PHP/JS 互通加密-解密

2019-03-24  本文已影响10人  Zero_75

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加密-解密

<!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>
上一篇下一篇

猜你喜欢

热点阅读