1. 程式人生 > >字串/字元陣列轉Base64編碼

字串/字元陣列轉Base64編碼

import sun.misc.BASE64Decoder; 
 
public class Base64 {
	
	/**
	 * 字串轉Base64編碼
	 * @param s
	 * @return
	 */
	public static String getBASE64(String s) { 
	if (s == null) return null; 
	return (new sun.misc.BASE64Encoder()).encode( s.getBytes() ); 
	} 
	/**
	 * 將 字元陣列 進行 BASE64 編碼 
	 * @param s
	 * @return
	 */
	public static String getBASE64Byte(byte[] s){
		if (s == null) return null; 
		return (new sun.misc.BASE64Encoder()).encode(s); 
	}
	 
	// 將 BASE64 編碼的字串 s 進行解碼 
	public static String getFromBASE64(String s) { 
	if (s == null) return null; 
	BASE64Decoder decoder = new BASE64Decoder(); 
	try { 
	byte[] b = decoder.decodeBuffer(s); 
	return new String(b); 
	} catch (Exception e) { 
	return null; 
	} 
	}
	public static void main(String[] args) {
		//String str = "123456";
		String str = "21b51cdb887c2d5a0e09e8c3187a18de66285bd316bcf36b6d43da152abfe91666f396068fac9efbd6bfac3f9e7d4745695b2e7bda02a2b04fb6790965eb65be568b6d3428f850ee9f648dc7cf1d97a73905dd584857194f0d8f9d2354bb9c938d6a9548d0220c03795d8070a9668700e9afcf7dd9ab2f8d7d757512358ab2ac";
		System.out.println(Base64.getBASE64(str));
		System.out.println(Base64.getFromBASE64(Base64.getBASE64(str)));
	}
}