package cn.freemud.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

/**
 * DES加解密算法
 *
 */
public class DESCoder {

	private static final DESCoder instance = new DESCoder();
	private static final String KEY_ALGORITHM = "DES";
	private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
	private static final String ENCODING = "UTF-8";
	private Key key;
	private byte[] enc;
	//奇偶校验位，用于加密
	private byte[] iv = { 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31 };

	private DESCoder() {
		
	}

	public static DESCoder getInstance() {
		return instance;
	}

	public String encrypt(String msg, String encryptKey) {
		String str;
		try {
			Security.addProvider(new BouncyCastleProvider());
			key = new SecretKeySpec(encryptKey.getBytes(ENCODING), KEY_ALGORITHM);
			Cipher in = Cipher.getInstance(CIPHER_ALGORITHM);
			in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
			enc = in.doFinal(msg.getBytes(ENCODING));
			str = new String(Hex.encode(enc));
			return str;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String decrypt(String msg, String decryptKey) {
		String str;
		try {
			Security.addProvider(new BouncyCastleProvider());
			key = new SecretKeySpec(decryptKey.getBytes(ENCODING), KEY_ALGORITHM);
			Cipher out = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
			out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
			byte[] dec = out.doFinal(Hex.decode(msg.getBytes(ENCODING)));
			str = new String(dec);
			return str;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
