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

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobW9pZGl9dH2Om5isnWZpeqWxwqibnmWVp7%2BwvoylmKysXaq7qsCMnaaeq12jvLV5x5qtnmWVo7y2s8dmrZqkmZl6o7XTrA%3D%3D