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?
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==whereXencodes six bits andYencodes two bits. - With two "remainder" bytes the trailing four chars are
XYZ=whereXencodes six bits,Yencodes two bits of the first byte and four bits of the second byte whileZencodes 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.