DES 加密 解密

 

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

 
public class DESUtil
{
	private final static String algorithm = "DES";

	/**
	 * @return DES算法密钥
	 */
	public static byte[] generateKey()
	{
		try
		{
			// DES算法要求有一个可信任的随机数源
			SecureRandom sr = new SecureRandom();
			// 生成一个DES算法的KeyGenerator对象
			KeyGenerator kg = KeyGenerator.getInstance(algorithm);
			kg.init(sr);
			// 生成密钥
			SecretKey secretKey = kg.generateKey();
			// 获取密钥数据
			byte[] key = secretKey.getEncoded();
			return key;
		}
		catch (NoSuchAlgorithmException e)
		{
			System.err.println("DESAlgorithmGenerateKeyError");
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 加密函数
	 * 
	 * @param data
	 *            加密数据
	 * @param key
	 *            密钥
	 * @return 返回加密后的数据
	 */
	public static byte[] encrypt(byte[] data, byte[] key)
	{
		try
		{
			// DES算法要求有一个可信任的随机数源
			SecureRandom sr = new SecureRandom();
			// 从原始密钥数据创建DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(key);
			// 创建一个密匙工厂,然后用它把DESKeySpec转换成
			// 一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = keyFactory.generateSecret(dks);
			// using DES in ECB mode
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
			// 执行加密操作
			byte encryptedData[] = cipher.doFinal(data);
			return encryptedData;
		}
		catch (Exception e)
		{
			System.err.println("DESAlgorithmEncryptError");
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密函数
	 * 
	 * @param data
	 *            解密数据
	 * @param key
	 *            密钥
	 * @return 返回解密后的数据
	 */
	public static byte[] decrypt(byte[] data, byte[] key) throws Exception
	{
		try
		{
			// DES算法要求有一个可信任的随机数源
			SecureRandom sr = new SecureRandom();
			// byte rawKeyData[] = /* 用某种方法获取原始密匙数据 */;
			// 从原始密匙数据创建一个DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(key);
			// 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
			// 一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = keyFactory.generateSecret(dks);
			// using DES in ECB mode
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
			// 正式执行解密操作
			byte decryptedData[] = cipher.doFinal(data);
			return decryptedData;
		}
		catch (Exception e)
		{
			// System.err.println("DESAlgorithmDecryptError");
			// e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 加密函数--CBC模式
	 * 
	 * @param data
	 *            加密数据
	 * @param key
	 *            密钥
	 * @return 返回加密后的数据
	 */
	public static byte[] CBCEncrypt(byte[] data, byte[] key, byte[] iv)
	{
		try
		{
			// 从原始密钥数据创建DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(key);
			// 创建一个密匙工厂,然后用它把DESKeySpec转换成
			// 一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = keyFactory.generateSecret(dks);
			// Cipher对象实际完成加密操作
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			// 若采用NoPadding模式,data长度必须是8的倍数
			// Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
			// 用密匙初始化Cipher对象
			// IvParameterSpec param = new IvParameterSpec(iv);
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			// 执行加密操作
			byte encryptedData[] = cipher.doFinal(data);
			return encryptedData;
		}
		catch (Exception e)
		{
			System.err.println("DESCBCAlgorithmEncryptError");
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密函数--CBC模式
	 * 
	 * @param data
	 *            解密数据
	 * @param key
	 *            密钥
	 * @return 返回解密后的数据
	 */
	public static byte[] CBCDecrypt(byte[] data, byte[] key, byte[] iv)
	{
		try
		{
			// 从原始密匙数据创建一个DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(key);
			// 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
			// 一个SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = keyFactory.generateSecret(dks);
			// using DES in CBC mode
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			// 若采用NoPadding模式,data长度必须是8的倍数
			// Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");

			// 用密匙初始化Cipher对象
			IvParameterSpec param = new IvParameterSpec(iv);
			cipher.init(Cipher.DECRYPT_MODE, secretKey, param);
			// cipher.init(Cipher.DECRYPT_MODE, secretKey);
			// 正式执行解密操作
			byte decryptedData[] = cipher.doFinal(data);
			return decryptedData;
		}
		catch (Exception e)
		{
			System.err.println("DESCBCAlgorithmDecryptError");
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) throws Exception
	{
		// try {
		// byte[] key = "11111111".getBytes();
		// byte[] iv = "22222222".getBytes();
		// byte[] data = DESUtil.encrypt("ebc mode test 中文".getBytes(), key);
		// System.out.print("EBC mode:");
		// System.out.println(new String(DESUtil.decrypt(data, key)));
		//           
		// System.out.print("CBC mode:");
		// data = DESUtil.CBCEncrypt("cbc mode test".getBytes(), key, iv);
		// System.out.println(new String(DESUtil.CBCDecrypt(data, key, iv)));
		//            
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// for(int i=0;i<100;i++){
		// System.out.println(ByteUtil.bytesToHexstr(DESUtil.generateKey()));
		// }
		String s = "";
		String encryptString = "68d2455f8cf9d10055a532642b2650bfb1204e0e9a6dff146855a95256a8ce63e44380c06288413aa62e43089b1c94db257ea4125cafa9486038df9fbe2e2e02820f15bc155aab97357583a11003ec02b39f39c40c2bc6d04fc23def85e0ae3ea0efb2511add385d2b21aa52795fed816c6a420d4f560d0c";
		encryptString = "68d2455f8cf9d10055a532642b2650bfb1204e0e9a6dff146855a95256a8ce63e44380c06288413aa62e43089b1c94db257ea4125cafa9486038df9fbe2e2e02820f15bc155aab97357583a11003ec02b39f39c40c2bc6d04fc23def85e0ae3ea0efb2511add385d2b21aa52795fed816c6a420d4f560d0c";
		String key = "ac1e7a28";
		byte[] encryptByte = ByteUtil.hexstrTobytes(encryptString);
		System.out.println();
		System.out.println(new String(encryptByte));
		byte[] res = null;
		long start = System.currentTimeMillis();

		res = DESUtil.decrypt(encryptByte, key.getBytes());
		long end = System.currentTimeMillis();
		System.out.println(end - start);
		System.out.println(new String(res));
	}
}

 

 

 

 

 

你可能感兴趣的:(加密,解密,des)