Base64 Decode Error Last Unit Does Not Have Enough Valid Bits

Base64 Decode Error Last Unit Does Not Have Enough Valid Bits

I have a certificate sent to me by my vendor in a .p7b file. I need to extract the certificates from it. So I run this on my cmd:

openssl pkcs7 -inform DER -outform PEM -in in.p7b -print_certs > cer_bundle.cer

I open up cer_bundle.cer and see three certificates. First two seem fine. The final certificate when put thru Base64.getDecoder().decode(myCert) throws up an error like:

java.lang.IllegalArgumentException: Last unit does not have enough valid bits\n\tat 
java.util.Base64$Decoder.decode0(Base64.java:734)\n\tat 
java.util.Base64$Decoder.decode(Base64.java:526)\n\tat 
java.util.Base64$Decoder.decode(Base64.java:549)\n\t
...

I then take contents of the cert and do this on my terminal

CERT=MIIFDj...
base64 --decode <<< $CERT

and I see an output on my console with no errors.

What's going on in java's Base64 decoder?

2

1 Answer

Base 64 encoding uses four characters to encode three bytes, so the length should be a multiple of four characters. If the input is a multiple of three bytes no padding is needed, otherwise = will be added. There will be one or two "remainder" bytes.

  • With one "remainder" byte, the trailing four chars are XY== where X encodes six bits and Y encodes two bits.
  • With two "remainder" bytes the trailing four chars are XYZ= where X encodes six bits, Y encodes two bits of the first byte and four bits of the second byte while Z encodes four bits of the second byte.

The error your getting indicates that the last four characters are essentially X=== (the = may be omitted) which makes no sense in base 64 encoding.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.