AES加密|AES加密 - 前端使用CryptoJS加密,后端使用Java解密-踩坑记录

【AES加密|AES加密 - 前端使用CryptoJS加密,后端使用Java解密-踩坑记录】因为有个需要加密的需求(虽然这种加密前端的密钥还是会被被人拿到,但是目的只是加强破解难度),前端需要把传入的密码加密,后端进行解密,于是乎用AES加密

记录一些遇到的异常(主要都是前端加密后的密文用Java解密的异常)
先上前端加密和后端解密的代码(前端解密 和 后端加密都差不多)
import CryptoJS from 'crypto-js'let key = CryptoJS.enc.Utf8.parse('1538663015386630'); let iv = CryptoJS.enc.Utf8.parse('sdaefascvfelk392'); export function encrypt() { let pwd = CryptoJS.enc.Utf8.parse('20000520WJ'); // let pwd = '20000520WJJ' console.log(pwd) // let srcs = CryptoJS.enc.Utf8.parse(pwd) let encrypted = CryptoJS.AES.encrypt(pwd, key, { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv:iv }) // 实际上这里得到的密文是用Base64编码过的,后面有个异常会说到 return encrypted.toString(); }

public static String decrypt(String cipherStr) { // 对于前端的密文要先base64解密 BASE64Decoder decoder = new BASE64Decoder(); IvParameterSpec iv = new IvParameterSpec(IV.getBytes()); SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); return new String(cipher.doFinal(decoder.decodeBuffer(cipherStr)), StandardCharsets.UTF_8); } catch (Exception e) { e.printStackTrace(); } return null; }

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
这个异常是因为一开始没有用BASE64解码,导致的,就是上面注释里的。在使用java进行加密的时候发现Base64编码后的密文和前端加密的一样,才得以解决
注: 加密的key 和 偏移量 iv 最好用16位

    推荐阅读