javaopensslbase64apache-commons-codec

Java String base64 encode algorithm to match openssl implementation


As part of attempting to configure SAML AuthN with a Google Search Appliance, I need to convert my response into base64. For proof of concept, I just used the debugger in IntelliJ IDEA to replace the string with a version generated by the openssl command:

openssl base64 -in inFileName -out outFileName

Now I need to get a version working without my direct intervention. I'm using the Apache commons base64 codec library (v. 1.4), charset UTF-8, lineLength 64, and the code looks like this:

Base64 encoder = new Base64(64);
signedSamlResponse = signedSamlResponse.replaceAll("[\n\r]","");
byte[] bytes = encoder.encode(signedSamlResponse.getBytes("UTF-8"));
signedSamlResponse = new String(bytes,0,bytes.length);

The result is quite close to what I need. If I do an openssl encryption on the string just before the apache library does it's thing (copy signedSamlResponse before line 3 executes), and then run a diff the two results they are nearly identical. The only difference is the second last character in the last line and this difference has been consistant across all my attempts.

Openssl version:

dD48L0Fzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPgo=

Apache version:

dD48L0Fzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==

What do I need to do to the byte array or the String it comes from in order to get the two results to match?


Solution

  • It looks like the openssl version ends with a "\n" - so having removed them all on your second line, you should add one at the end :)

    (Basically, the byte array from openssl has an extra 0x0a at the end; the Apache version you've given doesn't.)