1. 程式人生 > >JAVA 3DES加密/解密

JAVA 3DES加密/解密

3DES(或稱為Triple DES)是三重資料加密演算法(TDEA,Triple Data Encryption Algorithm)塊密碼的通稱。它相當於是對每個資料塊應用三次DES加密演算法。由於計算機運算能力的增強,原版DES密碼的金鑰長度變得容易被暴力破解;3DES即是設計用來提供一種相對簡單的方法,即通過增加DES的金鑰長度來避免類似的攻擊,而不是設計一種全新的塊密碼演算法

package com.qk365.utils;

import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

@SuppressWarnings("restriction")
public class EncryptUtils {

	private static final String Algorithm = "DESede"; // 定義加密演算法,可用,DES,DESede,Blowfish

	/**
	 * 3des解碼
	 * 
	 * @param value
	 *            待解密字串
	 * @param key
	 *            原始金鑰字串
	 * @return
	 * @throws Exception
	 */
	public static String Decrypt3DES(String value, String key) throws Exception {
		byte[] b = decryptMode(GetKeyBytes(key), Base64.decode(value));
		return new String(b);
	}

	/**
	 * 3des加密
	 * 
	 * @param value
	 *            待加密字串
	 * @param key
	 *            原始金鑰字串
	 * @return
	 * @throws Exception
	 */
	public static String Encrypt3DES(String value, String key) throws Exception {
		return byte2Base64(encryptMode(GetKeyBytes(key), value.getBytes()));
	}

	/**
	 * 計算24位長的密碼byte值,首先對原始金鑰做MD5算hash值,再用前8位資料對應補全後8位
	 * 
	 * @param strKey
	 *            金鑰
	 * @return
	 * @throws Exception
	 */
	public static byte[] GetKeyBytes(String strKey) throws Exception {
		if (null == strKey || strKey.length() < 1)
			throw new Exception("key is null or empty!");
		MessageDigest alg = MessageDigest.getInstance("MD5");
		alg.update(strKey.getBytes());
		byte[] bkey = alg.digest();
		int start = bkey.length;
		byte[] bkey24 = new byte[24];
		for (int i = 0; i < start; i++) {
			bkey24[i] = bkey[i];
		}
		for (int i = start; i < 24; i++) {// 為了與.net16位key相容
			bkey24[i] = bkey[i - start];
		}
		return bkey24;
	}

	/**
	 * 加密
	 * 
	 * @param keybyte為加密金鑰
	 *            ,長度為24位元組
	 * @param src
	 *            為被加密的資料緩衝區(源)
	 * @return
	 */
	public static byte[] encryptMode(byte[] keybyte, byte[] src) {
		try {
			// 生成金鑰
			SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); // 加密
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param keybyte
	 *            解密金鑰,長度為24位元組
	 * @param src
	 *            解密後的緩衝區
	 * @return
	 */
	public static byte[] decryptMode(byte[] keybyte, byte[] src) {
		try {
			// 生成金鑰
			SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
			// 解密
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.DECRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}

	/**
	 * 轉換成base64編碼
	 */
	public static String byte2Base64(byte[] b) {
		return Base64.encode(b);
	}

	/**
	 * 轉換成十六進位制字串
	 */
	public static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
			if (n < b.length - 1)
				hs = hs + ":";
		}
		return hs.toUpperCase();
	}

	/**
	 * 3DEC 加密解密測試
	 */
	public static void main(String[] args) throws Exception {
		String key = "jklasfjlksdghsdsad";
		String password = "123456";
		System.out.println("呼叫原始金鑰算加密結果:" + EncryptUtils.Encrypt3DES(password, key));
		String str = "8198h9Ejibg=";
		System.out.println("呼叫原始金鑰算解密結果:" + EncryptUtils.Decrypt3DES(str, key));
	}

}