解密的时候报错:
javax.crypto.BadPaddingException: Given final block not properly padded咋整?
详细错误信息:
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
at javax.crypto.Cipher.doFinal(DashoA6275)
at ThreeDesTool.decryptMode(ThreeDesTool.java:41) //就是这里的问题。一个解密的方法。
at Authentication.Authentication(Authentication.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
javax.crypto.BadPaddingException: Given final block not properly padded咋整?
详细错误信息:
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
at javax.crypto.Cipher.doFinal(DashoA6275)
at ThreeDesTool.decryptMode(ThreeDesTool.java:41) //就是这里的问题。一个解密的方法。
at Authentication.Authentication(Authentication.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
try {
//生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); //解密
Cipher c1 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
String encrypt = null;
try{
byte[] ret = encode(str.getBytes("UTF-8"),key);
encrypt = new String(Base64.encode(ret));
}catch(Exception e){
System.out.print(e);
encrypt = str;
}
return encrypt;
}
public static String DataDecrypt(String str,byte[] key){
String decrypt = null;
try{
byte[] ret = decode(Base64.decode(str),key);
decrypt = new String(ret,"UTF-8");
}catch(Exception e){
System.out.print(e);
decrypt = str;
}
return decrypt;
} 我们把方法的参数改成了字串,但是为什么要用UTF-8呢?不指定它的字节格式不行吗?大家知道,UTF-8是国际通用的字符编码,用它传输任何字串都不会有问题,通过它也可以很完美的解决J2EE的中文问题!所以我们最好用UTF-8编码,以减少不必要的麻烦。 注意,上面方法中当加密或者解密过程中,程序抛出异常,将返回原值,使得在调用方法失败时更方便的找出错误。 大家也可以利用其它的密钥,进行不同地方的加密解密 DES是一个相对比较老的加密算法,对于现在也不是最安全的,所以大家也可以利用别的加密算法进行加密解密,以得到更安全的系统。