作为一个前端菜鸡,今天碰到一个加密解密的坑,浪费了不少时间. 为了报仇,我决定再次拿起我的小本本,君子报仇十年不晚,先记下来.
先说坑,加密解密前端工作中很常见. 之前也加密过密码账户之类的,一切都顺畅无比,比如:
//vue中 mounted: function() { let x = encryptDes("123", this.$enkey);//加密 let x2 = decryptDes(x, this.$enkey); //解密 console.log(x); console.log(x2); }
输出结果:(看吧一切都那么顺利)
就在今天当我加密要一个"对象"的时候......出现了问题:
let obj = { test: 123 }; console.log(JSON.stringify(obj)); let x = encryptDes(JSON.stringify(obj), this.$enkey); let x2 = decryptDes(x, this.$enkey); console.log(x); console.log(x2);
结果输出了个这么个鬼东西:
这不科学啊,由于菜鸡是真的菜,导致我根本没见过这鬼东西,百度完了,丝毫没有线索,菜鸡我开始怀疑人生,突然灵光一现,难道就因为菜鸡我没"对象" ? obj=null了?
问了哈旁边后台的一个同事.说应该字符串的编码之类的问题 ,结果再用url解码解了下真的有结果:(JS中对URL进行转码与解码)
let obj = { test: 123 }; console.log(JSON.stringify(obj)); let x = encryptDes(JSON.stringify(obj), this.$enkey); let x2 = decryptDes(x, this.$enkey); console.log(x); console.log(x2); console.log(unescape(x2));
果然不是obj=null的事.
附加密的封装:
import cryptoJs from "crypto-js"; function stringToHex(str){ var val=""; for(var i = 0; i < str.length; i++){ if(val == "") val = str.charCodeAt(i).toString(16); else val += "," + str.charCodeAt(i).toString(16); } return val; } //base64加密 export const encryptBase64 = (message)=>{ var str = cryptoJs.enc.Utf8.parse(message); var encryptMsg = cryptoJs.enc.Base64.stringify(str); return encryptMsg } //base64解密 export const decryptBase64 = (message)=>{ var decryptMsg = cryptoJs.enc.Base64.parse(message); var parseStr = decryptMsg.toString(cryptoJs.enc.Utf8); return parseStr } // DES加密密 export const encryptDes = (message, key) => { message = encodeURIComponent(message) key = encodeURIComponent(key) var keyHex = cryptoJs.enc.Utf8.parse(key) var ivHex = cryptoJs.enc.Utf8.parse(key) var option = {iv: ivHex, mode: cryptoJs.mode.CBC, padding: cryptoJs.pad.Pkcs7} var encrypted = cryptoJs.DES.encrypt(message, keyHex, option) var msg = (encrypted.ciphertext.toString()) var b=msg.toUpperCase(); return (b) } // DES解密 export const decryptDes = (message, key) => { var keyHex = cryptoJs.enc.Utf8.parse(key) var ivHex = cryptoJs.enc.Utf8.parse(key) var decrypted = cryptoJs.DES.decrypt( { ciphertext: cryptoJs.enc.Hex.parse(message) }, keyHex, { iv: ivHex, mode: cryptoJs.mode.CBC, padding: cryptoJs.pad.Pkcs7 } ) return decrypted.toString(cryptoJs.enc.Utf8) }