DES加密 - 调用cipher.dofinal时出现badpadding异常

时间:2013-03-30 15:17:43

标签: android encryption apache-commons-codec

我有可用的Java代码。但在Android中,它不起作用。实际上我必须在java中加密一个字符串,通过https发送到android手机并在那里解密。我正在为base64使用apache commons编解码器。有什么建议为什么我得到BadPaddingException? 对于java和android来说,crypto.cipher是否有所不同

public class Cryptography {
private static final String CRYPTOGRAPHY_ALGO_DES = "DES";

private static Cipher cipher = null;
private static DESKeySpec keySpec = null;
private static SecretKeyFactory keyFactory = null;

public static String encrypt(String inputString, String commonKey)
        throws InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException {

    String encryptedValue = "";
    SecretKey key = getSecretKey(commonKey);

    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] inputBytes = inputString.getBytes();
    byte[] outputBytes = cipher.doFinal(inputBytes);

    encryptedValue =  new String(Base64.encodeBase64(outputBytes));
    return encryptedValue;
}

public static String decrypt(String encryptedString, String commonKey)
    throws InvalidKeyException, IllegalBlockSizeException,
    BadPaddingException, IOException {

String decryptedValue = "";
encryptedString = encryptedString.replace(' ', '+');

SecretKey key = getSecretKey(commonKey);

cipher.init(Cipher.DECRYPT_MODE, key); 

byte[] decodeBytes=Base64.decodeBase64(encryptedString.getBytes());

cipher.update(decodeBytes);
byte[] recoveredBytes = cipher.doFinal( );
System.out.println(" recovered bytes\t" + recoveredBytes);
decryptedValue = new String(recoveredBytes);
System.out.println(" decryptedvalue **strong text**\t" + decryptedValue);
return decryptedValue;

}

private static SecretKey getSecretKey(String secretPassword) {
SecretKey key = null;
try {
    cipher = Cipher.getInstance(CRYPTOGRAPHY_ALGO_DES);
    keySpec = new DESKeySpec(secretPassword.getBytes("UTF8"));
    keyFactory = SecretKeyFactory.getInstance(CRYPTOGRAPHY_ALGO_DES);
    key = keyFactory.generateSecret(keySpec);
} catch (Exception e) {
    e.printStackTrace();
    System.out.println("Error in generating the secret Key");
}
return key;
}

}
  

当我在java中执行所有这些函数时没有问题。但是当我在java中运行加密并在android中解密时,解密会给出异常

0 个答案:

没有答案