BASE64 encoding and decoding, BASE64 encoding and decoding
Dependent jar: import org. apache. commons. codec. binary. Base64;
BASE64 and other similar Encoding algorithms are usually used to convert binary data into text data to simplify storage or transmission. More specifically, the BASE64 algorithm is mainly used to convert binary data to the ASCII string format. The Java language provides a very good implementation of the BASE64 algorithm, namely the Apache Commons Codec toolkit. This article briefly describes how to use BASE64 and how it works.
The following code uses BASE64 to encode the string:
import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Base64; public class Base64Test { public static void main(String[] args){ String str = "Hello World"; try{ System.out.println("RESULT: " + encodeStr(str)); } catch(UnsupportedEncodingException e){ e.printStackTrace(); } } }
/*** Decrypt ** @ param pwd * @ return * @ see [Class, Class # method, class # member] */public static String decodeStr (String pwd) {Base64 base64 = new Base64 (); byte [] debytes = base64.decodeBase64 (new String (pwd ). getBytes (); return new String (debytes );} /*** encrypt ** @ param pwd * @ return * @ see [Class, Class # method, class # member] */public static String encodeStr (String pwd) {Base64 base64 = new Base64 (); byte [] enbytes = base64.encodeBase64Chunked (pwd. getBytes (); return new String (enbytes );
Output result:
- RESULT: SGVsbG8gV29ybGQ =
The output string is the 8-bit binary value of the "Hello world" string, which is connected together and grouped by 6 digits. Then, each group is converted into a separate number and mapped to the Base64 index.
binary dec Base64 010010 18 S 000110 6 G 010101 21 V 101100 44 s 011011 27 b 000110 6 G 111100 60 8 100000 32 g 010101 29 d 110110 54 2 111101 61 9 110010 50 y 011011 27 b 000110 6 G 010000 16 Q
Note: "=" is added at the end of the string, which indicates the end of the string encoding.