ZeroPadding 参照

发布时间 2023-08-19 20:03:27作者: runliuv

 

 

加密时要处理。

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