Base64 encoding and decoding

BASE64 and other similar encoding algorithms are often used to convert binary data to textual data for the purpose of simplifying storage or transmission . More specifically, the BASE64 algorithm is mainly used to convert binary data to ASCII string format.

Several common Base64 algorithms

1. Java's own Base64 algorithm

        To use Base64Encoder, I found that the class could not be found in Eclipse. The original Base64Encoder does not belong to the JDK standard library, but it is included in the JDK.

The solution to the problem: Project->Properties, select the Java Build Path setting item, then select the Libraries tab, Add External Jars and add %JAVA_HOME%\jre\lib\rt.jar.

/**
	 * Java自带的Base64算法
	 */
	public static void JDKBase64(String string) throws IOException{
		   //JDK 提供的Base64算法 对象
			BASE64Encoder encode=new BASE64Encoder();
			//Base64 编码
			String encoder = encode.encode(string.getBytes());
			System.out.println("encode: " + encoder);
		
			BASE64Decoder decode=new BASE64Decoder();
			byte[] decodeBuffer = decode.decodeBuffer(encoder);
			System.out.println("decode: " + new String(decodeBuffer));
	}

2. Base64 algorithm of commons-codec

    Import dependencies before use:

	<dependency>
		<groupId>commons-codec</groupId>
		<artifactId>commons-codec</artifactId>
		<version>1.5</version>
	</dependency>

    code:

/**
	 * commons-codec的Base64算法
	 */
	public static void  codecBase64(String string){
		//编码
		byte[] encodeBase64 = Base64.encodeBase64(string.getBytes());
		System.out.println("encode: " + Hex.encodeHexString(encodeBase64));
		
		//解码
		byte[] decodeBase64 = Base64.decodeBase64(encodeBase64);
		System.out.println("decode: " + new String(decodeBase64));
	}

    

3. Base64 algorithm of bouncycastle

Import dependencies before use:

	<dependency>
		<groupId>org.bouncycastle</groupId>
		<artifactId>bcprov-jdk15on</artifactId>
		<version>1.54</version>
	</dependency> 

code:

/**
	 *  Bouncy Castle的Base64算法
	 */
	public static void bcBase64(String string){
		//编码
		
		byte[] encode = org.bouncycastle.util.encoders.Base64.encode(string.getBytes());
		System.out.println("encode: " + new String(encode));
		//解码
		byte[] decode = org.bouncycastle.util.encoders.Base64.decode(encode);
		System.out.println("decode: " + new String(decode));
	}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325478859&siteId=291194637