package gaf3.core.util;

import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Base64;

public class PasswordUtil {
	
	private static final byte[] KEY_VALUE = {0x01,0x03,0x05,0x07,0x11,0x13,0x17,0x19,0x23,0x29,0x31,0x37,0x41,0x43,0x47,0x51};

	//private static BlockCipher _cipher = new AESEngine(); 存在线程安全问题
	private static KeyParameter key =new KeyParameter(KEY_VALUE);


	public static String encrypt(String prodata)
	{
		if(StringUtil.isNullOrEmpty(prodata))
			return prodata;
	
		String ret = null;
		try
		{
			BlockCipher _cipher = new AESEngine();
			PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(_cipher);
			cipher.init(true, key);
		
			byte[] input = prodata.getBytes();
			int outlen = cipher.getOutputSize(input.length);
			byte[] output = new byte[outlen];
			
			int outL = 0;

			outL = cipher.processBytes(input, 0, input.length, output, 0);
			cipher.doFinal(output, outL);
			
			ret = new String(Base64.encode(output));
		}
		catch(Exception ex)
		{
			throw new RuntimeException("密码加密错误！");
		}

		return ret;
	}
	public static String decrypt(String encdata)
	{
		if(StringUtil.isNullOrEmpty(encdata))
			return encdata;
		
		String ret = null;
		try
		{
			BlockCipher _cipher = new AESEngine();
			PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(_cipher);
			cipher.init(false, key);
		
			byte[] input = Base64.decode(encdata.getBytes());
			int outlen = cipher.getOutputSize(input.length);
			byte[] output = new byte[outlen];
			
			int outL = 0;

			outL = cipher.processBytes(input, 0, input.length, output, 0);
			outL += cipher.doFinal(output, outL);
			
			ret = new String(output,0,outL);
		}
		catch(Exception ex)
		{
			throw new RuntimeException("密码解密错误！");
		}

		return ret;
	}

	public static void main(String[] args) throws Exception{
//		String prodata = "admin";
//		String encdata = PasswordUtil.encrypt(prodata);
//		System.out.println(encdata);
		String encdata = "461P9LE6YCXMt+qLRo7vZQ==";
		String decdata = PasswordUtil.decrypt(encdata);
		System.out.println(decdata);
//		if(!prodata.equals(decdata))
//			throw new Exception("解密数据不匹配！");
		System.out.println("加解密成功！");
	}

}
