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

a 夏天 提交于 2020-02-26 03:55:13

问题


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


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/60370961/what-to-pass-in-cipher-dofinal-in-android-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!