小程序中经常会使用加解密提高安全性,此文采用对称加密,使用CryptoJS库,ECB模式
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 30 31 32 33 34 35 36 37 38 39
| import { CryptoJS } from './CryptoJS'
export const encrypt = (params, cryptoKey) => { const key = CryptoJS.enc.Utf8.parse(cryptoKey) const result = CryptoJS.TripleDES.encrypt(JSON.stringify(params), key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, }) return result.toString() }
export const decrypt = (result, cryptoKey) => { const key = CryptoJS.enc.Utf8.parse(cryptoKey) const decrypted = CryptoJS.TripleDES.decrypt(result, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, }).toString(CryptoJS.enc.Utf8)
try { return JSON.parse(decrypted) } catch (e) { return decrypted } }
|