发表于 2018-9-21 08:45:09

java aes CBC的填充方式发现

public static String aesEncrypt2(String appsecret, String data) throws Exception  {
//设置加密密钥  String key = appsecret.substring(16);
  System.out.println(key);
  SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
  //初始化向量
  System.out.println("md5: " + DigestUtils.md5Hex(appsecret).substring(0, 16));
  String iv = DigestUtils.md5Hex(appsecret).substring(0, 16);
  IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
  //设置加密模式
  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  //填充算法
  int blockSize = cipher.getBlockSize();
  byte[] dataBytes = data.getBytes();
  int plaintextLength = dataBytes.length;
  if (plaintextLength % blockSize != 0) {
  plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
  }
  byte[] plaintext = new byte;
  System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
  System.out.println("填充后长度=" + plaintext.length);
  for(int i = 0;i < plaintext.length; i++)
  System.out.print(plaintext + " ");
  //加密
  
      cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
  byte[] encrypted = cipher.doFinal(plaintext);
  System.out.println("");
  for(int i = 0;i < encrypted.length;i++)
  System.out.print(encrypted + " ");
  System.out.println("");
  return Base64.encodeBase64String(encrypted);
  }


页: [1]
查看完整版本: java aes CBC的填充方式发现