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 Wikipedia article.
Steps
- Enter Info and Name file
- Start up your editor, such as Notepad or vi, and enter the preliminaries, such as the class declaration and known constants. Name the file Base64.java.
- Those constant values are specified, so the article states, in the relevant RFCs. It is generally a good idea read all relevant RFCs before beginning coding.
- Lastly, we package the output, after padding it, by inserting CRLFs at the required 76-byte boundaries, using a separate subroutine for clarity.
- We can, if desired, add a main routine for testing purposes. This is usually a good idea before posting one's code for public consumption.
- Here is the finished module:
- Let's compile it, using javac, gcj, likes, or the like; and test, using the Hobbes quote from the Wikipedia article:
- It matches exactly! 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.
Tips
- Don't feel that you always have to understand something completely before coding. Things get clearer as you go along.
- Java is okay as a general purpose language, and for devices like cell phones may be a programmer's only option; but you might find Javascript's or Python's syntax to be more concise and powerful. Different languages have their own strengths and weaknesses.
- Try writing the companion decode() method for this module!
- While reading relevant RFCs is necessary for production code, the information overload can be overwhelming; sometimes the best way is to skim them, code according to what you understand, and then go back and check the functionality point-by-point against the RFC's mandatory requirements.
Related Articles
Sources and Citations
- https://en.wikipedia.org/wiki/Base64
- This research was made possible, in part, by a land grant from the City of the Sun, though the specifics of the research were not coordinated nor endorsed by COSF.