How to Encode a string with Base64 Encoding in Java

By Barry Nirmal and Rohit Nirmal
Say you have a plain string. It may have ASCII or binary data. To convert it into Base64, use the following line:

String kumar = Base64.encodeString ( plain_string );

This program will insert only LF after 76 characters on each line except the last line. The last line will end in = or == as the base 64 specs stipulate.

How to Decode a string that has Base64 Encoded data (Java)


Say you have a string that contains Base64 encoded data. To convert it back into original string, use the following line:

String kumar = Base64.decodeString ( encoded_string );


If your plain string is 1,000 bytes or 100,000 bytes, the output string after encoding may look like this
yv66vgAAADIASAoAEwAeCAAfCgAgACEHACIKAAQAIwoAJAAlCAAmCgAgACcJACgAKQcAKgoACgAe
CAArCgAKACwIAC0KAAoALgoALwAwCAAxBwAyBwAzAQAGPGluaXQ+AQADKClWAQAEQ29kZQEAD0xp
- - - - -
AAEAGwABABwAAAACAB0=

Say your file is a binary file e.g. a java class file. If you read all the bytes from it into a String and convert into Base64 you will get a String that when printed looks like the following:
yv66vgAAADIASAoAEwAeCAAfCgAgACEHACIKAAQAIwoAJAAlCAAmCgAgACcJACgAKQcAKgoACgAe
CAArCgAKACwIAC0KAAoALgoALwAwCAAxBwAyBwAzAQAGPGluaXQ+AQADKClWAQAEQ29kZQEAD0xp
bmVOdW1iZXJUYWJsZQEABG1haW4BABYoW0xqYXZhL2xhbmcvU3RyaW5nOylWAQAKRXhjZXB0aW9u
cwcANAEAClNvdXJjZUZpbGUBABV0ZXN0c3RhdGljbWV0aG9kLmphdmEMABQAFQEAFnRlc3RzdGF0
aWNtZXRob2QuY2xhc3MHADUMADYANwEAEGphdmEvbGFuZy9TdHJpbmcMABQAOAcAOQwAOgA7AQAI
- - - - -
DrYADbYAD7YAELEAAAABABcAAAAeAAcAAAAOAAYAEAAPABIAFAAUABoAFgA4ABcAVgAaABoAAAAE
AAEAGwABABwAAAACAB0=
Each line in above ends with "\n" not \r\n (CR-LF)

Last line ends with = or ==

The output String can be decoded by any Base64 decoder and it should give you back the original file. You can use the program given above for decoding.

Click here to download base64.zip that contains Base64.java.