493: Undecipherable



-About me-


Java Base64 encoding (sun.misc.Base64Encoder)

Dennis Guse

Today I would like to say some words about BASE64 encoding and JAVA. Let me introduce a cool class to encode a string: sun.misc.Base64Encoder This class seams to work quite all right for some weeks. So, today we transfered our JEE server from a linux to windows (not my idea). Till now I have assumed that the mythos of the JAVA plattform independence is not only a myth. During the check of the application (the deployed JEE project) it showed up error messages that the base64 coded strings doesn't match. On the first look everything seemed to be fine. The second showed up that the strings on the windows machine were one (!) character longer. Two hours later we found the problem: Does RFC 3548 say something about line feeds and carriage return?

So why does the base64 coded strings contain some?

The anwser is: Because the encode method of the *Base64Enconder split the string after some characters (I suppose at char 76 / 77, but I'm not quite sure). So if you switch the operation system and the new system uses another encoding for the line break, your old base64 encoded data is worthless.

To solve this problem I used the java mail api (cause JEE server needs to implement these):

 1StringOutputStream output = new StringOutputStream();
 2OutputStream encoding = MimeUtility.encode(output, "base64");
 3encoding.write("Hello World");
 4result = output.toString();
 7import java.io.IOException; import java.io.OutputStream;
10* @author Dennis Guse
13public class StringOutputStream extends OutputStream {
14  private StringBuffer data = new StringBuffer();
15  public StringOutputStream() {}
16  public String toString() {
17    return data.toString();
18  }
19  public void write(int b) throws IOException { data.append((char)b); } }

So a half day of work for nothing.... PS: Feel free to use this stuff.