JavaScript实现MD5、AES-CBC加密解密

CryptoJS是用JavaScript编写的加解密包,支持生成哈希、AES加密解密、多种编码方式。

安装

npm install crypto-js

哈希Hash

md5

var CryptoJS = require("crypto-js");
var hash = CryptoJS.MD5("123456");
console.log(hash.toString());
// e10adc3949ba59abbe56e057f20f883e

SHA256

var CryptoJS = require("crypto-js");

var hash = CryptoJS.SHA256("123456");
console.log(hash.toString());
// 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

密码

AES-CBC加密解密

var CryptoJS = require("crypto-js");

// 加密
plaintText = "123456"

// 十六进制
key = CryptoJS.enc.Hex.parse("1234567890123456")
iv = CryptoJS.enc.Hex.parse("1234567890123456")
var encrypted = CryptoJS.AES.encrypt(plaintText, key, {
    
    
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
// base64
console.log(encrypted.toString());
// cwFSKScoYr73L9Q8RpX7OQ==

// Hex
console.log(encrypted.ciphertext.toString());
// 73015229272862bef72fd43c4695fb39


// 解密
ciphertext = CryptoJS.enc.Hex.parse(encrypted.ciphertext.toString())
ciphertext = CryptoJS.enc.Base64.stringify(ciphertext)
var decrypted = CryptoJS.AES.decrypt(ciphertext, key, {
    
    
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
})
console.log(decrypted.toString(CryptoJS.enc.Utf8).toString())
// 123456


参考

https://github.com/brix/crypto-js
https://cryptojs.gitbook.io/docs/

猜你喜欢

转载自blog.csdn.net/lilongsy/article/details/131710291
今日推荐