JS实现常见加密算法
搬运: https://www.cnblogs.com/wjrblogs/p/13730128.html
DES
关键参数:密钥 key
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script>
<script>
//DES 加密
function encryptByDES(message, key){
var keyHex = CryptoJS.enc.Utf8.parse(key);
var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.ciphertext.toString();
}
//DES 解密
function decryptByDES(ciphertext, key){
var keyHex = CryptoJS.enc.Utf8.parse(key);
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Hex.parse(ciphertext)
}, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
var result_value = decrypted.toString(CryptoJS.enc.Utf8);
return result_value;
}
</script>
//调用
<script>
var message = '111111';//需要加密的数据
var key = '12345678';//加密密钥 key
var desMessage = 'xxxxxxxxxx';
//加密
desMessage = encryptByDES(message, key);
console.log(desMessage);
//解密
message = decryptByDES(desMessage,key)
console.log(message);
</script>
AES
关键参数:密钥 key,偏移量 iv
//首先要引入 https://github.com/sytelus/CryptoJS 中的两个文件
<script src="./rollups/aes.js"></script>
<script src="./components/pad-zeropadding.js"></script>//这个文件不是固定的,需要根据不同的填充方式而更改
<script>
function encryptByAES(data, key, iv){
var key = CryptoJS.enc.Latin1.parse(key);
var iv = CryptoJS.enc.Latin1.parse(iv);
var encrypted = CryptoJS.AES.encrypt(data,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding});
return encrypted.ciphertext.toString();
}
function decryptByAES(data, key, iv){
var key = CryptoJS.enc.Latin1.parse(key);
var iv = CryptoJS.enc.Latin1.parse(iv);
var decrypted = CryptoJS.AES.decrypt(data,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});
return decrypted.ciphertext.toString();
}
</script>
RSA
关键参数:公钥 PUBLIC_KEY,私钥 PRIVATE_KEY
<script src="https://cdn.bootcss.com/jsencrypt/3.0.0-beta.1/jsencrypt.js"></script>
<script>
var PUBLIC_KEY = '公钥';
var PRIVATE_KEY = '私钥';
var message = 'xxxxxxx';
var encryptmsg = 'testtest';
//使用公钥加密
function encryptByRSA(data, pub_key){
var encrypt = new JSEncrypt();
encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + pub_key + '-----END PUBLIC KEY-----');
var encrypted = encrypt.encrypt(data);
return encrypted;
}
//使用私钥解密
function decryptByRSA(data, pri_key){
var decrypt = new JSEncrypt();
decrypt.setPrivateKey('-----BEGIN RSA PRIVATE KEY-----'+ pri_key +'-----END RSA PRIVATE KEY-----');
var decrypted = decrypt.decrypt(encrypted);
return decrypted;
}
</script>