DES 加密解密方法

1.首先引入crypto-js.min.js库

<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script>

2.注册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();
}
//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;
}

3.加密明文

var str = '要加密的明文'
var key = '加密解密的密码'
// 加密
var desMessage = encryptByDES(str, key);
console.log(desMessage);

4.解密明文

var str = decryptByDES(desMessage,key)
console.log(str);

你可能感兴趣的:(js,des)