Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 629
Saturnian Avatar asked Apr 27 '26 02:04

Saturnian


1 Answers

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.

like image 143
Erik Avatar answered Apr 29 '26 17:04

Erik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!