关于Base64工具类并发问题

为减少对象创建次数,一般会做如下编码:

package com.***.frame.util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64Util {
	private static final BASE64Decoder decoder = new BASE64Decoder();
	private static final BASE64Encoder encoder = new BASE64Encoder();
	/**
	 * BASE64解密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decryptBASE64(String key) throws Exception {
		if(key==null||key.length()<1){
			return "";
		}
		return new String(decoder.decodeBuffer(key));
	}

	/**
	 * BASE64加密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptBASE64(String key) throws Exception {
		if(key==null||key.length()<1){
			return "";
		}
		return new String(encoder.encodeBuffer(key.getBytes()));
	}
}



此类看似没问题,在高并发下,存在解密失败的情况,无法还原出正确的原字符串。正确的做法如下:

	/**
	 * BASE64解密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decryptBASE64(String key) throws Exception {
		if(key==null||key.length()<1){
			return "";
		}
		return new String(new BASE64Decoder().decodeBuffer(key));
	}

	/**
	 * BASE64加密
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptBASE64(String key) throws Exception {
		if(key==null||key.length()<1){
			return "";
		}
		return new String(new BASE64Encoder().encodeBuffer(key.getBytes()));
	}



具体细节待查。

你可能感兴趣的:(apache,maven,sun)