美文网首页
AES跨平台如何解决C#PaddingMode.Zeros模式

AES跨平台如何解决C#PaddingMode.Zeros模式

作者: peteLee | 来源:发表于2019-03-27 11:37 被阅读0次

仅记录使用,原博客如下:
https://blog.csdn.net/OrangeJack/article/details/82913804

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;
    }
  }
}

相关文章

网友评论

      本文标题:AES跨平台如何解决C#PaddingMode.Zeros模式

      本文链接:https://www.haomeiwen.com/subject/kvzavqtx.html