`

使用Base64对字符串进行编码和解码

    博客分类:
  • Java
 
阅读更多

Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045RFC2049,上面有MIME的详细规范。Base64编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bitUUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码不仅比较简短,同时也具有不可读性,即所编码的数据不会被人用肉眼所直接看到。

 

Java中,SunApache都提供了API对字符串进行Base64编码和解码。

 

 

package com.test.day24.enanddecode;

import java.io.IOException;
import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 
 * java base64编码和解码的演示类 注:base64编码后通过url传递时,获得时"="会给替换掉, 处理方式:在编码前将"=","/","+"
 * 替换成别的字符,在解码之前替换回来
 * 
 * 
 * @author tw 2010-03-01
 * 
 */
public class Base64EnAndDeCode {

	/**
	 * 编码
	 * 
	 * @param filecontent
	 * @return String
	 */
	public static String encode(byte[] bstr) {
		return new BASE64Encoder().encode(bstr);
	}

	/**
	 * 解码
	 * 
	 * @param filecontent
	 * @return string
	 */
	public static byte[] decode(String str) {
		byte[] bt = null;
		try {
			BASE64Decoder decoder = new BASE64Decoder();
			bt = decoder.decodeBuffer(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bt;
	}

	public static void apacheDecoded() {
		String hello = "SGVsbG8gV29ybGQ=";

		//
		// Decode a previously encoded string using decodeBase64 method and
		// passing the byte[] of the encoded string.
		//
		byte[] decoded = Base64.decodeBase64(hello.getBytes());

		//
		// Print the decoded array
		//
		System.out.println(Arrays.toString(decoded));

		//
		// Convert the decoded byte[] back to the original string and print
		// the result.
		//
		String decodedString = new String(decoded);
		System.out.println(hello + " = " + decodedString);
	}

	public static void apacheBase64Encoded() {
		String hello = "Hello World";

		//
		// The encodeBase64 method take a byte[] as the paramater. The byte[]
		// can be from a simple string like in this example or it can be from
		// an image file data.
		//
		byte[] encoded = Base64.encodeBase64(hello.getBytes());

		//
		// Print the encoded byte array
		//
		System.out.println(Arrays.toString(encoded));

		//
		// Print the encoded string
		//
		String encodedString = new String(encoded);
		System.out.println(hello + " = " + encodedString);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 用sun base64对字符串进行编码
		Base64EnAndDeCode te = new Base64EnAndDeCode();
		String oldStr ="贞观长歌";
		oldStr = te.encode(oldStr.getBytes());
		System.out.println("----oldStr:" + oldStr);

		// 用sun base64对字符串进行解码
		String str = oldStr;
		String str2 = new String(te.decode(str));
		System.out.println("-----str2:" + str2);

		// 用apache codec对字符串进行Base64解码
		apacheDecoded();
		// 用apache codec对字符串进行Base64编码
		apacheBase64Encoded();
	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics