package com.cy.report.utils;

import java.net.URLDecoder;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;

public class Encrypt {

	public static final String KEY_ALGORITHM = "DES";
	public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";

	// ������ں���
	public static String decrypt(String content, byte[] key) throws Exception {
		byte[] bytes = null;
		byte[] encrypted = null;
		byte[] decrypted = null;
		String result = null;

		bytes = content.getBytes("UTF-8");
		encrypted = Base64.decodeBase64(bytes);

		decrypted = decryptBytes(encrypted, key);
		result = new String(decrypted, "UTF-8");

		return result;
	}

	private static byte[] decryptBytes(byte[] data, byte[] key)
			throws Exception {
		Key k = toKey(key);
		Cipher cipher;
		byte[] bytes = null;
		cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, k);
		bytes = cipher.doFinal(data);

		return bytes;
	}

	//
	private static Key toKey(byte[] key) throws Exception {
		DESKeySpec des = null;
		SecretKeyFactory keyFactory = null;
		SecretKey secretKey = null;
		des = new DESKeySpec(key);
		keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
		secretKey = keyFactory.generateSecret(des);
		return secretKey;
	}

	public static String getDesString(String str) throws Exception {
//		str = URLDecoder.decode(str);
//		//System.out.println(str);
		byte[] key = "F3Hm+B1g8Tj7254ascdSS45dncniPt3gmmODSF0V".getBytes();

		String data = Encrypt.decrypt(str, key);
		//System.out.println("解密后:" + new String(data));
		return new String(data);
	}

	public static void main(String[] args) throws Exception {
		String str = "pmlS9dACD06vp4wKM9T%2FoBMVfuGm9yEgIOkBJ5qpbdDk7%2BZ2Tema3rUZzrslaRaqDrVEwn4kqpQ%3D";
		getDesString(str);
	}
}