JavaScript实现DES的加密与解密
1.需要引入JS包:cryptojs.js
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script>
2.js的DES加密
//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();
}
3.js的DES解密
//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;
}
4.运用实例
var message = '18616563858'; //需要加密的数据
var key = 'pptv'; //加密key
//加密
desMessage = encryptByDES(message, key);
console.log(desMessage);
//解密
message = decryptByDES(desMessage,key)
console.log(message);