How to Encode a String to Base64 With Java


Base64 is a method of encoding every 3 bytes of input into 4 bytes of output; it is commonly used to encode photos or audio to send in emails (though the days of 7-bit transmission lines are mostly over), and a way to hide webpage authentication (usernames and passwords) from casual snooping. Here is an example of how to code a Base64 encoder in Java, a multi-platform programming language. This example, and the test coding string, is borrowed from the .

Part 1

 on How to Encode a String to Base64 With Java

1

 on How to Encode a String to Base64 With Java

2
Name the file Base64.java.

 on How to Encode a String to Base64 With Java

3
It is generally a good idea read all relevant RFCs before beginning coding. public class Base64 { private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/"; private static final int splitLinesAt = 76;

 on How to Encode a String to Base64 With Java

4
Therefore, we must use the getBytes() method of String in order to convert the Unicode characters of the current locale to bytes before the encoding begins. But, for example, if you're working on a Japanese document in an American English locale, you will need to specify the locale for the output of getBytes(), such as getBytes("UTF-8").

 on How to Encode a String to Base64 With Java

5
Java's modulo operator, %, comes in handy here. Let's also declare the subroutine name and parameters while we're at it.

 on How to Encode a String to Base64 With Java

6
Note that if no padding is needed, none is added, since we take the modulus of 3 a second time, turning a 3 into a 0. public static byte[] zeroPad(int length, byte[] bytes) { byte[] padded = new byte[length]; // initialized to zero by JVM System.arraycopy(bytes, , padded, , bytes.length); return padded; } public static String encode(String string) { String encoded = ""; byte[] stringArray; try { stringArray = string.getBytes("UTF-8"); // use appropriate encoding string! } catch (Exception ignored) { stringArray = string.getBytes(); // use locale default rather than croak } int paddingCount = (3 - (stringArray.length % 3)) % 3; stringArray = zeroPad(stringArray.length + paddingCount, stringArray);

 on How to Encode a String to Base64 With Java

7
packing three bytes at a time into a 24-bit integer, then extracting out 6-bit indices into the coding string. These numbers aren't magic: 24 divides into 6 exactly 4 times, and 6 bits can hold values from 0 to 63, which can index into any value in the 64-byte coding string. for (int i = ; i < stringArray.length; i += 3) { int j = ((stringArray[i] & 0xff) << 16) + ((stringArray[i + 1] & 0xff) << 8) + (stringArray[i + 2] & 0xff); encoded = encoded + base64code.charAt((j >> 18) & 0x3f) + base64code.charAt((j >> 12) & 0x3f) + base64code.charAt((j >> 6) & 0x3f) + base64code.charAt(j & 0x3f); }

 on How to Encode a String to Base64 With Java

8
return splitLines(encoded.substring(, encoded.length() - paddingCount) + "==".substring(, paddingCount)); } public static String splitLines(String string) { String lines = ""; for (int i = ; i < string.length(); i += splitLinesAt) { lines += string.substring(i, Math.min(string.length(), i + splitLinesAt)); lines += "\r\n"; } return lines; }

 on How to Encode a String to Base64 With Java

9
This is usually a good idea before posting one's code for public consumption. public static void main(String[] args) { for (int i = ; i < args.length; i++) { System.err.println("encoding \"" + args[i] + "\""); System.out.println(encode(args[i])); } }

 on How to Encode a String to Base64 With Java

10
public class Base64 { private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/"; private static final int splitLinesAt = 76; public static byte[] zeroPad(int length, byte[] bytes) { byte[] padded = new byte[length]; // initialized to zero by JVM System.arraycopy(bytes, , padded, , bytes.length); return padded; } public static String encode(String string) { String encoded = ""; byte[] stringArray; try { stringArray = string.getBytes("UTF-8"); // use appropriate encoding string! } catch (Exception ignored) { stringArray = string.getBytes(); // use locale default rather than croak } // determine how many padding bytes to add to the output int paddingCount = (3 - (stringArray.length % 3)) % 3; // add any necessary padding to the input stringArray = zeroPad(stringArray.length + paddingCount, stringArray); // process 3 bytes at a time, churning out 4 output bytes // worry about CRLF insertions later for (int i = ; i < stringArray.length; i += 3) { int j = ((stringArray[i] & 0xff) << 16) + ((stringArray[i + 1] & 0xff) << 8) + (stringArray[i + 2] & 0xff); encoded = encoded + base64code.charAt((j >> 18) & 0x3f) + base64code.charAt((j >> 12) & 0x3f) + base64code.charAt((j >> 6) & 0x3f) + base64code.charAt(j & 0x3f); } // replace encoded padding nulls with "=" return splitLines(encoded.substring(, encoded.length() - paddingCount) + "==".substring(, paddingCount)); } public static String splitLines(String string) { String lines = ""; for (int i = ; i < string.length(); i += splitLinesAt) { lines += string.substring(i, Math.min(string.length(), i + splitLinesAt)); lines += "\r\n"; } return lines; } public static void main(String[] args) { for (int i = ; i < args.length; i++) { System.err.println("encoding \"" + args[i] + "\""); System.out.println(encode(args[i])); } } }

 on How to Encode a String to Base64 With Java

11
$ gcj -C Base64.java $ java Base64 "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure."

 on How to Encode a String to Base64 With Java

12
encoding "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure." TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=

 on How to Encode a String to Base64 With Java

13
That either means both programs are wrong, or they're both more or less right. At this point you might want to revisit the Wikipedia article, and read the linked RFCs to see if we missed anything.