Different base64 encoding validation in java.util and apach-commons

101 Views Asked by At

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

There are 1 best solutions below

5
Federico klez Culloca On

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.