1

Let's consider the following codebase:

val str = "contextId" println(org.apache.commons.codec.binary.Base64.isBase64(str)) String(java.util.Base64.getDecoder().decode(str)) 

It prints:

true Exception in thread "main" java.lang.IllegalArgumentException: Last unit does not have enough valid bits at java.base/java.util.Base64$Decoder.decode0(Base64.java:867) at java.base/java.util.Base64$Decoder.decode(Base64.java:566) at java.base/java.util.Base64$Decoder.decode(Base64.java:589) ... 

It looks contradictory for me.

Could you please explain this behaviour?

1 Answer 1

1

The documentation for isBase64 states (emphasis mine)

Tests a given String to see if it contains only valid characters within the Base64 alphabet.

It says nothing about the fact that the string can be decoded or has an appropriate length. Hence it returns true.

On the other hand java.util.Base64.getDecoder().decode(str) actually tries to decode the string, but fails because the string doesn't have an appropriate length.

Sign up to request clarification or add additional context in comments.

5 Comments

Well, so Is there validation method which answers if it is possible to decode in boolean format without exception handling ?
@gstackoverflow Not Java/Kotlin specific, but check out stackoverflow.com/q/8571501/6395627
@Slaw Yes, I've read exactly it. I've taken it from stackoverflow.com/a/14217969/2674303
@gstackoverflow I'd say go with John Skeet's answer instead.
@Federico klez Culloca I am surprised if there are no library for that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.