遇到问题是在微信小程序里面(当然和网页的js也是一样),都是使用库CryptoJS。发现它默认输出是16进制,但是服务器解析时候是需要Base64的。
可以到第三方网站测试 http://tool.chacuo.net/cryptaes
加密模式:CBC 填充pkcs7或pkcs5 key = "keykeykeykeykeyk"; iv = '1234567887654321'; str ="这是测试数据"; hex结果"890645269898FC89010F7651372C0F38817DD57BAA12552EFAF418398F3E08CA" base64结果"iQZFJpiY/IkBD3ZRNywPOIF91XuqElUu+vQYOY8+CMo="
解决需要转成Base64的解决方法:
var fun_aes = require('../../utils/libs/aes.js') var key = fun_aes.CryptoJS.enc.Utf8.parse("keykeykeykeykeyk"); var iv = fun_aes.CryptoJS.enc.Utf8.parse('1234567887654321'); function AES_Encrypt(word) { var srcs = fun_aes.CryptoJS.enc.Utf8.parse(word); var encrypted = fun_aes.CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: fun_aes.CryptoJS.mode.CBC, padding: fun_aes.CryptoJS.pad.Pkcs7 }); var hexStr = encrypted.ciphertext.toString().toUpperCase(); console.log('hexStr->' + hexStr); var oldHexStr = fun_aes.CryptoJS.enc.Hex.parse(hexStr); // 将密文转为Base64的字符串 var base64Str = fun_aes.CryptoJS.enc.Base64.stringify(oldHexStr); console.log('base64Str->' + base64Str); //这里根据需求返回 base64Str 或 hexStr(解密时有小小差别) return hexStr; var srcs = word; //若上面加密返回的hexStr,需打开下面两行注释,再次处理 //var encryptedHexStr = fun_aes.CryptoJS.enc.Hex.parse(word); // var srcs = fun_aes.CryptoJS.enc.Base64.stringify(encryptedHexStr); var decrypt = fun_aes.CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: fun_aes.CryptoJS.mode.CBC, padding: fun_aes.CryptoJS.pad.Pkcs7 }); var decryptedStr = decrypt.toString(fun_aes.CryptoJS.enc.Utf8); var value = decryptedStr.toString(); console.log('value->'+value); return value;