reliance on Jar:import org.apache.commons.codec.binary.Base64;
BASE64 and other similar coding algorithms are commonly used to convert binary data into textual data, which is intended to simplify storage or transmission. More specifically, the BASE64 algorithm is primarily used to convert binary data into ASCII string formats. The Java language provides a very good implementation of the BASE64 algorithm, the Apache Commons codec toolkit. This article will briefly describe how to use BASE64 and how it works.
Here we encode the string using BASE64:
Importjava.io.UnsupportedEncodingException;Importorg.apache.commons.codec.binary.Base64; Public classBase64test { Public Static voidMain (string[] args) {String str= "Hello World"; Try{ System.out.println ("RESULT:" + encodestr (str)); } Catch(unsupportedencodingexception e) {e.printstacktrace (); } } }
/*** Decryption * *@parampwd *@return * @see[Class, Class # method, Class # member]*/ Public Staticstring Decodestr (string pwd) {Base64 base64=NewBase64 (); byte[] debytes = Base64.decodebase64 (NewString (PWD). GetBytes ()); return NewString (debytes); } /*** Encryption * *@parampwd *@return * @see[Class, Class # method, Class # member]*/ Public Staticstring Encodestr (string pwd) {Base64 base64=NewBase64 (); byte[] Enbytes =base64.encodebase64chunked (Pwd.getbytes ()); return NewString (enbytes);
The output is:
- RESULT: sgvsbg8gv29ybgq=
The above output string is a 8-bit binary value of the "Hello World" string that is concatenated and then grouped in 6 bits. Each group is then converted to a separate number and mapped to the index of the Base64.
binary 010010 000110 6010101 101100 011011 000110 6 1111008 100000 010101 110110 2 111101 9 110010 011011 000110 6 010000Q
Note: The string is finally prefixed with "=", which means the end of the string encoding.
BASE64 encoding and decoding