Given final block not properly padded异常
问题描述:windows下运行正常,linux下就解密异常
//防止linux下 随机生成key
SecureRandom secureRandom = SecureRandom.getInstance(“SHA1PRNG” );
secureRandom.setSeed(keycontent.getBytes());
// 根据密钥初始化密钥生成器
kgen.init(keyNum, secureRandom);
具体详情见代码
- 加密方法
public static String getSecretContent(String appSecret, String content) {
KeyGenerator kg;
try {
kg = KeyGenerator.getInstance("AES");
// kg.init(128);//要生成多少位,只需要修改这里即可128, 192或256
//SecureRandom是生成安全随机数序列,password.getBytes()是种子,只要种子相同,序列就一样,所以生成的秘钥就一样。
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(appSecret.getBytes());
kg.init(128,random);
SecretKey sk = kg.generateKey();
byte[] format = sk.getEncoded();
//转秘钥
SecretKeySpec sKeySpec = new SecretKeySpec(format, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
byte[] bjiamihou = cipher.doFinal(content.getBytes("utf-8"));
String sercetContent = byteToHexString(bjiamihou);
return sercetContent;
} catch (Exception e) {
logger.info("参数加密异常,{}", new Object[]{ExceptionUtils.getFullStackTrace(e)});
throw new ApiReqException("504", "参数加密异常");
}
}
解密方法
public static String resolveContet(String appSecret, String content) {
KeyGenerator kg = null;
try {
byte[] miwen = hexStringToByte(content);
kg = KeyGenerator.getInstance("AES");
// kg.init(128);//要生成多少位,只需要修改这里即可128, 192或256
//SecureRandom是生成安全随机数序列,password.getBytes()是种子,只要种子相同,序列就一样,所以生成的秘钥就一样。
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(appSecret.getBytes());
kg.init(128, random);
SecretKey sk = kg.generateKey();
byte[] keyb = sk.getEncoded();
SecretKeySpec sKeySpec = new SecretKeySpec(keyb, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sKeySpec);//初始化为解密模式的密码器
byte[] reContent = cipher.doFinal(miwen);
String s = new String(reContent,"utf-8");
return s;
} catch (Exception e) {
logger.info("aes解密出现异常详情,{}",new Object[]{ExceptionUtils.getFullStackTrace(e)});
throw new ApiReqException(ApiReqErrorCode.StatusCode.ERROR_500.getCode(),
ApiReqErrorCode.StatusCode.ERROR_500.getMsg());
}
}
十六进制string转二进制byte[]
public static byte[] hexStringToByte(String s) {
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
}
}
return baKeyword;
}
字节转字符
public static String byteToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String strHex = Integer.toHexString(bytes[i]);
if (strHex.length() > 3) {
sb.append(strHex.substring(6));
} else {
if (strHex.length() < 2) {
sb.append("0" + strHex);
} else {
sb.append(strHex);
}
}
}
return sb.toString();
}