1

我有有效的 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中解密时,解密给出异常

4

0 回答 0