Pooja Singh
Pooja Singh

Reputation: 159

What to pass in cipher.doFinal in Android/Java?

Android code

String apiResponse = "EcUZvMif

Method:

protected void decryptDataWithAES(String apiResponse, String key) {
        try {
            es(StandardCharsets.UTF_8);


            byte[] decodedResult = Base64.decode(apiResponse, Base64.NO_WRAP);

           terSpec = new IvParameterSpec(first16ByteArray);

            SecretKeySpec skey = new SecretKeySpec(byteArray, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(DECRYPT_MODE, skey, ivParameterSpec);

            String decryptString = new String(cipher.doFinal(byteArray), StandardCharsets.UTF_8);
            showLog("JSON: " + decryptString);

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

Exception: javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT

[wefopwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwefpwfpkpewfpkoewfkowf ewfwefwef]bhdfuiyh

Upvotes: 0

Views: 688

Answers (2)

Rahul Gaur
Rahul Gaur

Reputation: 1699

Here is a static method to decrypt using AES with secretKey

private final static String AES_PADDING = "AES/ECB/PKCS5PADDING"; //this need to be same as DECRYPTION 
private String secretKey = "Your secret key"; //your secret key

//DecryptString
@SuppressLint("GetInstance")
public static String AESDecryptionString(String encryptedStringData) {
    Cipher decipher = null;
    byte[] encryptedString = encryptedStringData.getBytes(StandardCharsets.ISO_8859_1);
    String returnData = encryptedStringData;
    try {
        decipher = Cipher.getInstance(AES_PADDING);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        e.printStackTrace();
    }
    byte[] decryption;
    try {
        assert decipher != null;
        decipher.init(Cipher.DECRYPT_MODE, secretKey);
        decryption = decipher.doFinal(encryptedString);
        returnData = new String(decryption);
    } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
        e.printStackTrace();
    }
    return returnData;
}

You can also use my library to encrypt/decrypt string using AES

Upvotes: 0

Lena Bru
Lena Bru

Reputation: 13947

You are trying to decrypt the "key", I think you need to decrypt the apiResponse

Also you need the exact same IV the message was encrypted with, otherwise you won't be able to decrypt

Upvotes: 1

Related Questions