⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 des.java

📁 这是本人曾经在公司里用的,内部开发框架,基于struts+hibernate今天分享给大家
💻 JAVA
字号:
/**
 * 
 */
package cn.bway.common;

import java.security.Security;
import java.security.spec.KeySpec;

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

/**
 * @author Kson
 *
 */
public class DES {

	private Cipher ecipher;

	private Cipher dcipher;

	private final String ALGORITHM = "DES";

	SecretKey secretKey = null;

	String password;

	private final byte[] KEYBYTES = new byte[] { (byte) 0x62, (byte) 0x34,
			(byte) 0x32, (byte) 0x38, (byte) 0x32, (byte) 0x62, (byte) 0x34,
			(byte) 0x37 };

	public DES() {

		try {
			Security.addProvider(new com.sun.crypto.provider.SunJCE());

			// Create the key
			KeySpec keySpec = new DESKeySpec(KEYBYTES);
			secretKey = SecretKeyFactory.getInstance(ALGORITHM, "SunJCE")
					.generateSecret(keySpec);

			ecipher = Cipher.getInstance(secretKey.getAlgorithm());
			dcipher = Cipher.getInstance(secretKey.getAlgorithm());

			// Create the ciphers
			ecipher.init(Cipher.ENCRYPT_MODE, secretKey);
			dcipher.init(Cipher.DECRYPT_MODE, secretKey);
		} catch (javax.crypto.NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (java.security.spec.InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (java.security.NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (java.security.NoSuchProviderException e) {
			e.printStackTrace();
		} catch (java.security.InvalidKeyException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 只能内部使用该构造器,主要用于根密钥的生成
	 *
	 * @param password  密钥
	 */
	private DES(String password) {

		if (password == null || password == "") {
			password = "s#A1j_";
		} else {
			this.password = password;
		}

		secretKey = generateKey(password);

		try {
			ecipher = Cipher.getInstance(secretKey.getAlgorithm());
			dcipher = Cipher.getInstance(secretKey.getAlgorithm());

			// Create the ciphers
			ecipher.init(Cipher.ENCRYPT_MODE, secretKey);
			dcipher.init(Cipher.DECRYPT_MODE, secretKey);
		} catch (javax.crypto.NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (java.security.NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (java.security.InvalidKeyException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据用户提供的密码串生成根密钥
	 *
	 * @param password 用户提供的密码串
	 * @return
	 */
	private SecretKey generateKey(String password) {
		KeySpec keySpec = null;
		SecretKey key = null;

		try {
			Security.addProvider(new com.sun.crypto.provider.SunJCE());

			// Create the key
			keySpec = new DESKeySpec(password.getBytes());
			key = SecretKeyFactory.getInstance(ALGORITHM, "SunJCE")
					.generateSecret(keySpec);
		} catch (java.security.spec.InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (java.security.InvalidKeyException e) {
			e.printStackTrace();
		} catch (java.security.NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (java.security.NoSuchProviderException e) {
			e.printStackTrace();
		}

		return key;
	}

	/**
	 * 加密字节数组
	 *
	 * @param arrB 需加密的字节数组
	 * @return 加密后的字节数组
	 * @throws Exception
	 */
	public byte[] encrypt(byte[] arrB) throws Exception {
		return ecipher.doFinal(arrB);
	}

	/**
	 * 加密字符串
	 *
	 * @param strIn 需加密的字符串
	 * @return 加密后的字符串
	 * @throws Exception
	 */
	public String encrypt(String strIn) throws Exception {
		return StringUtils.byteArr2HexStr(encrypt(strIn.getBytes()));
	}

	/**
	 * 解密字节数组
	 *
	 * @param arrB 需解密的字节数组
	 * @return 解密后的字节数组
	 * @throws Exception
	 */
	public byte[] decrypt(byte[] arrB) throws Exception {
		return dcipher.doFinal(arrB);
	}

	/**
	 * 解密字符串
	 *
	 * @param strIn 需解密的字符串`
	 * @return 解密后的字符串
	 * @throws Exception
	 */
	public String decrypt(String strIn) throws Exception {
		return new String(decrypt(StringUtils.hexStr2ByteArr(strIn)));
	}

	/**
	 * 得到所生成的对称密钥的byte[]
	 *
	 * @param key  对称密钥
	 * @return     对称密钥的byte[]存储
	 */
	private byte[] getBytesAsKey() {

		// Get the bytes of the key
		byte[] keyBytes = null;

		try {
			String str = encrypt(password);
			SecretKey key = generateKey(str);
			keyBytes = key.getEncoded();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return keyBytes;
	}

	/**
	 * 显示所生成的对称密钥的byte[]
	 *
	 * @param keyBytes  对称密钥的byte[]存储
	 */
	private void displayKeyBytes(byte[] keyBytes) {

		int numBytes = keyBytes.length;

		System.out.println("对称密钥的byte[]的长度:" + numBytes);

		StringBuffer buf = new StringBuffer();
		buf.append("private final byte[] KEYBYTES = new byte[]{");
		for (int i = 0; i < numBytes; i++) {

			buf.append("(byte)0x");

			int intTmp = keyBytes[i];
			//把负数转换为正数
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			//小于0F的数需要在前面补0
			if (intTmp < 16) {
				buf.append("0");
			}
			buf.append(Integer.toString(intTmp, 16));

			if (i != (numBytes - 1)) {
				buf.append(", ");
			}
		}

		buf.append("};");

		System.out.println(buf.toString());
	}

	/**
	 * 根据口令生成根密钥
	 *
	 * @param password
	 * @return
	 */
	public byte[] generateKeyBytes(String password) {
		SecretKey key = generateKey(password);

		return getBytesAsKey();
	}

	/**
	 * 根据对称密钥的byte[]取回SecretKey
	 *
	 * @param keyBytes  对称密钥的byte[]
	 * @return  转换回来的SecretKey
	 */
	private SecretKey getBackKey(byte[] keyBytes) {

		// The bytes can be converted back to a SecretKey
		SecretKey key = new SecretKeySpec(keyBytes, ALGORITHM);

		return key;
	}

	/**
	 * 单元测试方法
	 * @param args
	 */
	public static void main(String[] args) {

		//生成主密钥
		//    DES desEncrypter = new DES("ASPireMK");
		//   desEncrypter.displayKeyBytes(desEncrypter.getBytesAsKey());

		//单元测试
		DES desEncrypter = new DES();
		desEncrypter.test();
	}

	/**
	 * 单元测试方法,打印对指定字符串加密后和解密后的字符串
	 */
	private void test() {
		try {
			String strOriginal = "manage";
			System.out.println("Original data : " + strOriginal);
			System.out.println("Length: " + strOriginal.length());

			String strEncrypt = encrypt(strOriginal);
			System.out.println("Encrypted data: " + strEncrypt);
			System.out.println("Length: " + strEncrypt.length());

			String strDecrypt = decrypt("9ae1ce4a23b6ecaf");
			System.out.println("Decrypted data: " + strDecrypt);
			System.out.println("Length: " + strDecrypt.length());

			System.out.println("====================================");

			String strOriginal1 = "admin";
			System.out.println("Original data : " + strOriginal1);
			System.out.println("Length: " + strOriginal1.length());

			String strEncrypt1 = encrypt(strOriginal1);
			System.out.println("Encrypted data: " + strEncrypt1);
			System.out.println("Length: " + strEncrypt1.length());

			String strDecrypt1 = decrypt("620daf4c3364f45f");
			System.out.println("Decrypted data: " + strDecrypt1);
			System.out.println("Length: " + strDecrypt1.length());

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -