JavaScript实现DES加密解密

摘要:js-des-encrypt

JavaScript 实现DES加密解密

1. 引入依赖crypto-js

1
npm install crypto-js
1
const CryptoJS = require('crypto-js');

或者

1
<script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

2. 编写代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//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.toString();
}

//DES解密
function decryptByDES(ciphertext, key) {
var keyHex = CryptoJS.enc.Utf8.parse(key);
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
}, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}

// 加密方法测试
const key = '1sdfa_123)(*';
const en = encryptByDES("admin", key);
console.log(en); // vV2ssD+Fb1I=
const de = decryptByDES(en, key);
console.log(de);