public static Stringdecrypt(String data, String key, String iv, String encodingFormat)throws Exception {
// initialize();
//被加密的数据
byte[] dataByte = Base64.decodeBase64(data.getBytes());
//加密秘钥
byte[] keyByte = Base64.decodeBase64(key.getBytes());
//偏移量
byte[] ivByte = Base64.decodeBase64(iv.getBytes());
try {
int base =16;
if (keyByte.length % base !=0) {
int groups = keyByte.length / base + (keyByte.length % base !=0 ?1 :0);
byte[] temp =new byte[groups * base];
Arrays.fill(temp, (byte)0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
// Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec spec =new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
// 初始化
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
System.out.println("==================:" +dataByte);
byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length >0) {
String result =new String(resultByte, encodingFormat);
return result;
}
return null;
}catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (InvalidParameterSpecException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (BadPaddingException e) {
e.printStackTrace();
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
特别说明:
后面我加上了这个,加上前端把请求顺序调了一下就好了 不知道有没有关系
int base =16;
if (keyByte.length % base !=0) {
int groups = keyByte.length / base + (keyByte.length % base !=0 ?1 :0);
byte[] temp =new byte[groups * base];
Arrays.fill(temp, (byte)0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
网友评论