Base64 編碼解碼

import org.apache.commons.codec.binary.Base64;
/*import pt.log.LoggerUtil;*/

public class Base64Util {
	/**
	 * 對字符串BASE64編碼
	 * 
	 * @param res
	 *            源字符串
	 * @param charset
	 *            字符集
	 * @return
	 */
	public static String encode(String res, String charset) {
		try {
			Base64 base = new Base64();
			if ((res != null) && (!"".equals(res))) {
				return new String(base.encode(res.getBytes(charset)));
			}
			return "";
		} catch (Exception e) {
			/*LoggerUtil.outLog(Level.INFO,
					"pt.util.Base64Util.encode(String,String):BASE64編碼出錯。");*/
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 對字符串BASE64編碼
	 * 
	 * @param res
	 *            源字符串字節數組
	 * @return
	 */
	public static byte[] encodeByte(byte[] res) {
		try {
			Base64 base = new Base64();
			return base.encode(res);
		} catch (Exception e) {
			/*LoggerUtil.outLog(Level.INFO,
					"pt.util.Base64Util.encodeByte(byte[]):BASE64編碼出錯。");*/
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * BASE64字符串解碼
	 * 
	 * @param str
	 *            BASE64字符串
	 * @param charset
	 *            字符集
	 * @return
	 */
	public static String decode(String str, String charset) {
		try {
			return new String(new Base64().decode(str.getBytes()), charset);
		} catch (Exception e) {
			/*LoggerUtil.outLog(Level.INFO,
					"pt.util.Base64Util.decode(String,String):BASE64解碼出錯。");*/
		}
		return "";
	}

	/**
	 * BASE64字符串解碼
	 * 
	 * @param str
	 *            BASE64字符串
	 * @return
	 */
	public static byte[] decode(String str) {
		try {
			return new Base64().decode(str.getBytes());
		} catch (Exception e) {
			/*LoggerUtil.outLog(Level.INFO,
					"pt.util.Base64Util.decode(String):BASE64解碼出錯。");*/
		}
		return null;
	}

	/**
	 * BASE64字符串解碼
	 * 
	 * @param str
	 *            BASE64字符串字節數組
	 * @return
	 */
	public static byte[] decodeByte(byte[] str) {
		try {
			return new Base64().decode(str);
		} catch (Exception e) {
			/*LoggerUtil.outLog(Level.INFO,
					"pt.util.Base64Util.decodeByte(byte):BASE64解碼出錯。");*/
		}
		return null;
	}
	
	
	public static void main(String[] args)  throws Exception{
		//String str = "JIqE+LLBnbSgomWP3JjHu5DvnpfEa5RKt2SM8Q9igVyYCQwtTuYZayFgkA47ytA118+2Wwk9YX4wMX150FMVgRgXtpVGGpj+RTpRCVUgN+/V7jy2h4SPaOSTk/Pc/EO3Zc8V0QCiQPH5bafSbQjWGw==";
		String str="v6q+37rs19bU9ta1y7DXqNPDt6LGsdDFz6Kx7bHgusUxMzAyMDMxNjExMDA3NzQ2DQpGSER+MDAyNDAyMTQ0NH42NjQ2LTE2MTAyMC0wMDE1O7aptaUwMDYzNzA0ODQ0LTAwNjM3Mjg5MTM7xr7WpDk5MTg5MDA2ODUtOTkxODkwMDY4NjsoNjY0Ni3Mxsm9vq3TqrK/KTsoMDAwMDEwNDc0Nik7";
		System.out.println(new String(decode(str,"gbk")));
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章