其他分享
首页 > 其他分享> > 前端对称加密方案

前端对称加密方案

作者:互联网

import CryptoJS from 'crypto-js'; import Utf8 from 'crypto-js/enc-utf8'; import ECB from 'crypto-js/mode-ecb'; import Pkcs7 from 'crypto-js/pad-pkcs7';
/** * AES 加密 * * @author ShiPengCheng * @date 2020-07-23 * @param {*} word * @param {*} keyStr */ export const encrypt = (word, keyStr) => { // 每次获取之前都会检查是否存在于当前的key集合中(此处是定义了全局的参数 不参与打包) const encryption_Key = window.service.encryptionkeys; // 可设置为随机获取key 防止出现规律获取 // 暂时去调随时获取key const keyIndex = Math.floor((Math.random() * encryption_Key.length)); if (encryption_Key.length == 0) { return '请设置加密key'; } keyStr = keyStr ? keyStr : encryption_Key[encryption_Key.length - 1]; const key = Utf8.parse(keyStr); const srcs = Utf8.parse(word); const encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: ECB, padding: Pkcs7 }); return encrypted.toString(); };
/** * AES 解密 * * @author ShiPengCheng * @date 2020-07-23 * @param {*} word */ export const decrypt = word => { // 每次获取之前都会检查是否存在于当前的key集合中 const encryption_Key = window.service.encryptionkeys; let decrtptWords = ''; encryption_Key.map(item => { if (getDecrtptWords(word, item)) { decrtptWords = getDecrtptWords(word, item); } }); return decrtptWords; };
/** * AES解密字符处理 * * @author ShiPengCheng * @date 2020-07-24 * @param {*} word * @param {*} itemkey */ const getDecrtptWords = (word, itemkey) => { try { const key = Utf8.parse(itemkey); const decryptText = CryptoJS.AES.decrypt(word, key, { mode: ECB, padding: Pkcs7 }); if (Utf8.stringify(decryptText).toString()) { return Utf8.stringify(decryptText).toString(); } } catch (error) {} };

标签:加密,Key,word,前端,keyStr,key,encryption,对称,const
来源: https://www.cnblogs.com/S-pcholder/p/16372887.html