npm加密算法模块实践:crypto-js模块以及md5模块的使用(AES、md5)

在终端中输入如下命令行:

npm install crypto-js --save-dev
npm install md5 --save-dev

引入模块

const CryptoJS = require('crypto-js')
const MD5 = require('crypto-js/md5')

AES加密算法的使用

const AESencrypt = (message) => {
    let result
    let src = CryptoJS.enc.Utf8.parse(message)
    result = CryptoJS.AES.encrypt(src, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })
    return result.ciphertext.toString().toUpperCase()
}

AES解密算法的使用

const AESdecrypt = (secret) => {
    let encryptedHexStr = CryptoJS.enc.Hex.parse(secret);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    let decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr;
}

md5加密算法的使用,md5算法无法解密

const MD5encrypt = (message)=>{
    let result
    result = MD5(message)
    return result+''
}

完整代码
mima.js

const CryptoJS = require('crypto-js')
const MD5 = require('crypto-js/md5')



// AES密钥以及偏移量
const key = CryptoJS.enc.Utf8.parse('[email protected]')
const iv = CryptoJS.enc.Utf8.parse('[email protected]')



// AES加密
const AESencrypt = (message) => {
    let result
    let src = CryptoJS.enc.Utf8.parse(message)
    result = CryptoJS.AES.encrypt(src, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })
    return result.ciphertext.toString().toUpperCase()
}


// AES解密
const AESdecrypt = (secret) => {
    let encryptedHexStr = CryptoJS.enc.Hex.parse(secret);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    let decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr;

}

// MD5加密
const MD5encrypt = (message)=>{
    let result
    result = MD5(message)
    return result+''
}

export  {
    AESencrypt,
    AESdecrypt,
    MD5encrypt
}

总结:
如何判断算法是否是加密算法?
答:最简单的判断方法是:看该算法是否可以解密

你可能感兴趣的:(前端算法,javascript,npm,前端)