android 中 DES 解密出现javax.crypto.BadPaddingException: pad block corrupted
私房菜
移动开发领域优质创作者
博客专家认证 2018-11-12 10:38:06 最近在android 中实验DES 的加解密,加密过程是没问题的,但是在解密的时候出现:
12-09 23:58:12.299 1681 1939 W System.err: javax.crypto.BadPaddingException: pad block corrupted
12-09 23:58:12.299 1681 1939 W System.err: at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$BufferedGenericBlockCipher.doFinal(BaseBlockCipher.java:1306)
12-09 23:58:12.299 1681 1939 W System.err: at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:1139)
12-09 23:58:12.299 1681 1939 W System.err: at javax.crypto.Cipher.doFinal(Cipher.java:1741)
代码如下:
public static Cipher getCipher(int mode, String alg, String key) {
if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE)
return null;
SecretKey secretKey = getSecretKey(alg, key);
if (secretKey == null)
return null;
if (TextUtils.equals(alg, "DES") || TextUtils.equals(alg, "DESede")) {
key = key.substring(0, 8);
}
try {
IvParameterSpec ivp = new IvParameterSpec(key.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance(alg + "/CBC/PKCS5Padding");
cipher.init(mode, secretKey, ivp);
return cipher;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static byte[] encrypt(byte[] rawValue, Cipher cipher) {
if (cipher == null) {
return null;
}
byte[] encrypted = null;
try {
encrypted = cipher.doFinal(rawValue);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return encrypted;
}