0

I am trying to encode and decode a String using android.util.Base64, but it gives a bad base-64 error.

String str = "EOKF36syRBtB11VgyChkNjc1HxRrajT7XXaxZfnVzPkV57K3b9yqkS284Ovb9uWzXgGeY2bxA3IySGfdOHiPAQ==F/v6hcTiU1sd975XHfDsz8o0rboujM77n7KwRMidobOLbo5ghUT/IFcxElUc8CirdZxaCaS3zs/CfRKRsXwbFNYd"; Base64.decode(str,Base64.NO_WRAP); 

I am trying to decode the string using the following flags (NO_CLOSE, DEFAULT, NO_PADDING, URL_SAFE) but it give the same error.

Please help me to solve my problem.

2
  • Rule #1 of Android debugging: always paste your error if you want to receive good answers. I tested here and I receive a Base64DecoderException with message encoded getValue has invalid trailing byte, which means that the chunk being decoded at the time isn't finalized by an equal sign (61) or new line (10) byte. If it is really worth it—or want to learn more—you can debug/breakpoint what is being done in the Base64 class and also see the Base64 spec online. Commented Jun 19, 2017 at 13:25
  • Make sure you don't have space between your string. that may give you bad string error. Commented Jul 21, 2022 at 4:31

3 Answers 3

7

I use below method for decoding base64 strings and it works fine.

private String decodeBase64(String coded){ byte[] valueDecoded= new byte[0]; try { valueDecoded = Base64.decode(coded.getBytes("UTF-8"), Base64.DEFAULT); } catch (UnsupportedEncodingException e) { } return new String(valueDecoded); } 
Sign up to request clarification or add additional context in comments.

Comments

3

Your encoded string seems to be corrupted. Try decoding the string you have defined in the variable 'str' using an online base64 decoder. The result is garbled text.

1 Comment

Without more details this seems to be the best we can answer.
1

Place a correct base64 String and try like below

 String img = "your_base_64_string"; byte[] decodedString = Base64.decode(img, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.