runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  704 随笔 :: 0 文章 :: 125 评论 :: 97万 阅读
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

 

 

加密时要处理。

解密时,不需要额外处理,直接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

posted on   runliuv  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2020-08-19 docker on windows v19 红色启动不了
点击右上角即可分享
微信分享提示