package gaf3.core.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class EncryptUtil {
	private static Log LOG = LogFactory.getLog(EncryptUtil.class);
	
	public static final String WRAP_PREFIX = "WRAPPED:";

	public static String CryptWrap(String plaintext){
		if(isWrapped(plaintext)||plaintext == null){
			return plaintext;
		}
		try{
			String encStr = PasswordUtil.encrypt(plaintext);;
			return WRAP_PREFIX+encStr;
		}catch(Exception ex){
			LOG.warn("CrypeWrap failed:" + ex.getMessage());
			return plaintext;
		}
	}
	public static String CryptUnwrap(String plaintext){
		if(!isWrapped(plaintext)){
			try{
				return PasswordUtil.decrypt(plaintext);
			}catch(Exception ex){
				LOG.warn("CrypeUnwrap failed:"+ex.getMessage());
				return plaintext;
			}
		}
		try{
			String encStr = plaintext.substring(WRAP_PREFIX.length());
			return PasswordUtil.decrypt(encStr);
		}catch(Exception ex){
			LOG.warn("CrypeUnwrap failed:"+ex.getMessage());
			return plaintext;
		}
	}

	private static boolean isWrapped(String data){
		if(data == null) return false;
		return data.startsWith(WRAP_PREFIX);
	}
	public static void main(String[] args) throws Exception{
		String encdata = "WRAPPED:xybFQ8HYlaeoDqPie7LniQ==";
		String decdata = CryptUnwrap(encdata);
		System.out.println(decdata);
		System.out.println("加解密成功！");
	}
}
