Java_DES加解密

import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.Cipher;

import org.springframework.util.StringUtils;

/**
 * Utility for encrypting and decrypting Strings.
 */
public class CryptUtils {

	public static String DEFAULT_KEY = "ids2012";

	private Cipher encryptCipher = null;

	private Cipher decryptCipher = null;

	private final char[] sHexCharactors = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public CryptUtils(String key) {
		if(StringUtils.isEmpty(key)){
			key = Constant.DES_DEFAULT_KEY;
		}
		init(key);
	};

	public CryptUtils() {
		init(Constant.DES_DEFAULT_KEY);
	};
	
	private void init(String keyString) {
		Key key = null;
		try {
			key = getKey(keyString.getBytes());
			this.encryptCipher = Cipher.getInstance("DES");
			this.encryptCipher.init(Cipher.ENCRYPT_MODE, key);

			this.decryptCipher = Cipher.getInstance("DES");
			this.decryptCipher.init(Cipher.DECRYPT_MODE, key);
		} catch (Exception e) {
		}
	}

	/**
	 * Convert byte array to string, byte[]{8, 16} will be converted to 0811.
	 * 
	 * @param array
	 * @return
	 */
	public String toHexString(byte[] array) {
		if (null == array) {
			return null;
		}
		int length = array.length;
		StringBuilder sb = new StringBuilder(length << 1);
		for (int i = 0; i < length; i++) {
			int b = array[i];

			int low = b & 0xf;
			b = b >> 4;
			int high = b & 0xf;

			sb.append(sHexCharactors[high]);
			sb.append(sHexCharactors[low]);
		}

		return sb.toString();
	}

	/**
	 * Convert string to byte array.
	 * 
	 * @param s
	 * @return
	 * @see #toHexString(byte[])
	 */
	public byte[] toByteArray(String s) {
		if (null == s) {
			return null;
		}
		String sub = s;
		int len = sub.length();

		byte[] array = new byte[len >> 1];
		for (int i = 0, j = 0; i < len; i += 2, j++) {
			char highChar = sub.charAt(i);
			char lowChar = sub.charAt(i + 1);

			String str = new String(new char[] { highChar, lowChar });

			int value = Integer.parseInt(str, 16);
			array[j] = (byte) value;
		}
		return array;
	}

	/**
	 * Encrypt a byte array.
	 * 
	 * @param arrB
	 * @return null if any exception is thrown.
	 */
	public byte[] encrypt(byte[] arrB) {
		try {
			return encryptCipher.doFinal(arrB);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * Encypt a string.
	 * 
	 * @param strIn
	 * @return
	 */
	public String encrypt(String strIn) {
		if (null == strIn) {
			return null;
		}
		byte[] data = strIn.getBytes();
		byte[] encryptData = encrypt(data);
		return toHexString(encryptData);
	}

	/**
	 * Decrypt a byte array.
	 * 
	 * @param arrB
	 * @return null if any exception is thrown.
	 */
	public byte[] decrypt(byte[] arrB) {
		try {
			return decryptCipher.doFinal(arrB);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * Decrypt the string.
	 * 
	 * @param strIn
	 * @return null if the string passed in is null or exception is thrown.
	 */
	public String decrypt(String strIn) {
		byte[] data = toByteArray(strIn);
		if (null == data) {
			return null;
		}
		byte[] decryptData = decrypt(data);
		if (null == decryptData) {
			return null;
		}

		return new String(decryptData);
	}

	private Key getKey(byte[] data) throws Exception {
		byte[] keyArray = new byte[8];

		for (int i = 0; i < data.length && i < keyArray.length; i++) {
			keyArray[i] = data[i];
		}
		Key key = new javax.crypto.spec.SecretKeySpec(keyArray, "DES");
		return key;
	}

	/**
	 * 隨機生成6位密碼
	 * 
	 * @return
	 */
	public static String generatePassword() {
		String[] pa = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
				"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
		StringBuffer sb = new StringBuffer("");
		for (int i = 0; i < 6; i++) {
			sb.append(pa[(Double.valueOf(Math.random() * pa.length).intValue())]);
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		CryptUtils c = new CryptUtils("ids2012");
		System.out.println(c.encrypt("12345678"));
		System.out.println(c.decrypt("3b5aac201dadafe1617c5187b85f3159"));
	}
}

發佈了26 篇原創文章 · 獲贊 40 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章