加密时要处理。
解密时,不需要额外处理,直接NoPadding.
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; public class AesUtil { private static byte[] enKey = new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; private static byte[] enIV = new byte[] {5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}; private static SecretKeySpec keyspec = new SecretKeySpec(enKey, "AES"); private static IvParameterSpec ivspec = new IvParameterSpec(enIV); public static String encode(String data) { try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(); int length = dataBytes.length; //计算需填充长度 if (length % blockSize != 0) { length = length + (blockSize - (length % blockSize)); } byte[] plaintext = new byte[length]; //填充 System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] result = cipher.doFinal(plaintext); return new BASE64Encoder().encodeBuffer(result); } catch (Exception e) { e.printStackTrace(); return null; } } public static String decode(String data) { try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); try { byte[] getByte = new BASE64Decoder().decodeBuffer(data); byte[] original = cipher.doFinal(getByte); return new String(original, StandardCharsets.UTF_8); } catch (Exception ex) { ex.printStackTrace(); return null; } } catch (Exception ex) { ex.printStackTrace(); return null; } } }
ok
分类:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2020-08-19 docker on windows v19 红色启动不了