493: Undecipherable

-Blog-

-Projects-

-About me-

-RSS-

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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
StringOutputStream output = new StringOutputStream();
OutputStream encoding = MimeUtility.encode(output, "base64");
encoding.write("Hello World");
result = output.toString();


import java.io.IOException; import java.io.OutputStream;
/**
*
* @author Dennis Guse
*
*/
public class StringOutputStream extends OutputStream {
  private StringBuffer data = new StringBuffer();
  public StringOutputStream() {}
  public String toString() {
    return data.toString();
  }
  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.