前端 crypto-js 3DES 加解密
3DES(又叫Triple DES)是三重数据加密算法(TDEA,Triple Data Encryption Algorithm)块密码的通称。它相当于是对每个数据块应用三次DES加密算法。密钥长度是128位,192位(bit),如果密码位数少于等于64位,加密结果与DES相同。原版DES容易被破解,新的3DES出现,增加了加密安全性,避免被暴力破解。它同样是对称性加密,同样涉及到加密编码方式,及填充方式。包括3DES-ECB
、3DES-CBC
、3DES-CTR
、3DES-OFB
、3DES-CFB
。
JavaScript加密库Crypto-JS
:https://github.com/brix/crypto-js
CryptoJS (crypto.js) 为 JavaScript 提供了各种各样的加密算法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<script src="./crypto-js/src/core.js"></script>
<script src="./crypto-js/src/evpkdf.js"></script>
<script src="./crypto-js/src/cipher-core.js"></script>
<script src="./crypto-js/src/md5.js"></script>
<script src="./crypto-js/src/aes.js"></script>
<script src="./crypto-js/src/tripledes.js"></script>
<script src="./crypto-js/src/enc-base64.js"></script>
<script src="./crypto-js/src/enc-utf16.js"></script>
<script src="./crypto-js/src/format-hex.js"></script>
<script src="./crypto-js/src/hmac.js"></script>
<script src="./crypto-js/src/lib-typedarrays.js"></script>
<script src="./crypto-js/src/mode-cfb.js"></script>
<script src="./crypto-js/src/mode-ctr.js"></script>
<script src="./crypto-js/src/mode-ctr-gladman.js"></script>
<script src="./crypto-js/src/mode-ecb.js"></script>
<script src="./crypto-js/src/mode-ofb.js"></script>
<script src="./crypto-js/src/pad-ansix923.js"></script>
<script src="./crypto-js/src/pad-iso10126.js"></script>
<script src="./crypto-js/src/pad-iso97971.js"></script>
<script src="./crypto-js/src/pad-nopadding.js"></script>
<script src="./crypto-js/src/pad-zeropadding.js"></script>
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button id="md5">MD5</button>
<button id="tripledes">3DES</button>
<script>
$(function() {
$("#md5").click(function(){
console.log("测试");
//MD5
var md5Str = CryptoJS.MD5("key").toString(CryptoJS.enc.Hex).toUpperCase();
console.log("MD5后得到的字符串:%s", md5Str)
return false;
});
$("#tripledes").click(function(){
//3DES
// Encrypt
var encrypted = CryptoJS.TripleDES.encrypt('AppBlog.CN', CryptoJS.enc.Utf8.parse('123456'), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).ciphertext
encrypted = CryptoJS.enc.Base64.stringify(encrypted);
console.log("3DES加密得到的字符串:%s", encrypted)
// Decrypt
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse(encrypted)
}, CryptoJS.enc.Utf8.parse('123456'), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log("3DES解密得到的字符串:%s", decrypted.toString(CryptoJS.enc.Utf8))
return false;
});
});
</script>
</body>
</html>
注:在使用crypto-js进行解密的时候,可能会报Malformed UTF-8 data
错误
报错原因:des解密时,如果加密数据不是8的整数倍就会报上述错误
解决办法:将数据加密后,再进行base64进行加密,解密时首先通过base64进行解密,然后再进行des解密即可
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/12/frontend-crypto-js-3des-encryption-and-decryption/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
共有 0 条评论