`

java 两种加密工具类

阅读更多

 

import java.security.Key;

import javax.crypto.Cipher;

/**
 * DES加密和解密工具,可以对字符串进行加密和解密操作 。
 */
public class CipherUtil {

	/** 默认密钥 */
	private static String strDefaultKey = "na*dd&^1.vw/.,qp22";

	/**
	 * <pre>
	 * 加密字符串 ,使用默认密钥
	 * @param strIn  
	 * 字符串 
	 * @return 加密后的字符串
	 * </pre>
	 */
	public static String encrypt(String strIn) {
		return encrypt(strIn, strDefaultKey);
	}

	/**
	 * <pre>
	 * 加密字符串 
	 * @param strIn  字符串 
	 * @param strKey 使用指定的密钥
	 * @return 加密后的字符串
	 * </pre>
	 */
	public static String encrypt(String strIn, String strKey) {

		try {
			//loadEncrypt(strKey);
			Key key = getKey(strKey.getBytes());
			Cipher encryptCipher = Cipher.getInstance("DES");
			encryptCipher.init(Cipher.ENCRYPT_MODE, key);
			
			byte[] arrB = encryptCipher.doFinal(strIn.getBytes());
			int iLen = arrB.length;
			// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
			StringBuffer sb = new StringBuffer(iLen * 2);
			for (int i = 0; i < iLen; i++) {
				int intTmp = arrB[i];
				// 把负数转换为正数
				while (intTmp < 0) {
					intTmp = intTmp + 256;
				}
				// 小于0F的数需要在前面补0
				if (intTmp < 16) {
					sb.append("0");
				}
				sb.append(Integer.toString(intTmp, 16));
			}
			return sb.toString();
		} catch (Exception e) {
			System.out.println("error : "+strIn+" ,"+e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * <pre>
	 * 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB) 
	 * 互为可逆的转换过程 
	 * @param strIn 需要转换的字符串 
	 * @return 转换后的byte数组
	 * </pre>
	 */
	private static byte[] hexStr2ByteArr(String strIn) throws Exception {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;
		// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}
	
	
	/**
	 * <pre>
	 * 解密字符串 ,使用默认密钥
	 * @param strIn  字符串 
	 * @return 解密后的字符串
	 * </pre>
	 */
	public static String decrypt(String strIn) throws Exception {
		return decrypt(strIn, strDefaultKey);
	}
	
	/**
	 * <pre>
	 * 解密字符串
	 * @param strIn  字符串 
	 * @param strKey  使用指定的密钥
	 * @return 解密后的字符串
	 * </pre>
	 */
	public static String decrypt(String strIn, String strKey) {
		try {
			//loadDecrypt(strKey);
			
			Key key = getKey(strKey.getBytes());
			Cipher decryptCipher = Cipher.getInstance("DES");
			decryptCipher.init(Cipher.DECRYPT_MODE, key);
			
			byte[] data = decryptCipher.doFinal(hexStr2ByteArr(strIn));
			return new String(data);
		} catch (Exception e) {
			System.out.println("error : "+strIn+" ,"+e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * <pre>
	 * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位 
	 * @param arrBTmp  构成该字符串的字节数组 
	 * @return 生成的密钥
	 * </pre>
	 */
	private static Key getKey(byte[] arrBTmp) throws Exception {
		// 创建一个空的8位字节数组(默认值为0)
		byte[] arrB = new byte[8];
		// 将原始字节数组转换为8位
		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}
		// 生成密钥
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
		return key;
	}

	public static void main(String[] args) {
		try {
			long start = System.currentTimeMillis();

			String test1 = "qUzwFIVJB4eY24jklPH8Xl39DYd2a7Be";
			System.out.println("加密前的字符:" + test1);
			System.out.println("加密后的字符:" + CipherUtil.encrypt(test1));
			System.out.println("解密后的字符:" + CipherUtil.decrypt(CipherUtil.encrypt(test1)));
			System.out.println("");
			
			String test2 = "123456789";
			System.out.println("加密前的字符:" + test2);
			System.out.println("加密后的字符:" + CipherUtil.encrypt(test2, "leeme32nz"));
			System.out.println("解密后的字符:" + CipherUtil.decrypt(CipherUtil.encrypt(test2, "leeme32nz"),"leeme32nz"));
			System.out.println("");
			
			String test3 = "O8dW2G6cu8EeQlW7YC4hJARiYXbsLx5BysbwkAji611mkWR235+MsvpF3Chc7uG7UJDDCjlto2jx";
			System.out.println("加密前的字符:" + test3);
			System.out.println("加密后的字符:" + CipherUtil.encrypt(test3, "leeme32nz"));
			System.out.println("解密后的字符:" + CipherUtil.decrypt(CipherUtil.encrypt(test3, "leeme32nz"), "leeme32nz"));
			System.out.println("");
			
			long end = System.currentTimeMillis();
			System.out.println("耗时 = " + (end - start));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

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

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 加密常用类
 */
public class EncryptUtil {
	// 密钥是16位长度的byte[]进行Base64转换后得到的字符串
	public static String key = "NyvYt54GStGEQ==MLmtOpF4x";

	public static void main(String[] args) throws Exception {
		long start = System.nanoTime();
		System.out.println(encrypt("qUzwFIVJB4eY24jklPH8Xl39DYd2a7BeiTcbHConJA"));
		System.out.println(decrypt(encrypt("qUzwFIVJB4eY24jklPH8Xl39DYd2a7BeiTcbHConJA")));
		System.out.println("");
		System.out.println(encrypt("qUzwFIVJB4eY24jklPH8Xl39DYd2a7BeiTcbHConJA"));
		System.out.println(decrypt(encrypt("qUzwFIVJB4eY24jklPH8Xl39DYd2a7BeiTcbHConJA")));
		System.out.println("");
		System.out.println(encrypt("qUzwFIVJB4eY24jklPH8Xl+39DYd2a7BeiTcbHConJA"));
		System.out.println(decrypt(encrypt("qUzwFIVJB4eY24jklPH8Xl+39DYd2a7BeiTcbHConJA")));
		System.out.println("");
		long end = System.nanoTime();
		System.out.println("end = " + ((end - start) / 1000000));
	}
	
	/**
	 * <pre>
	 * 加密方法
	 * @param xmlStr  需要加密的消息字符串
	 * @return 加密后的字符串
	 * </pre>
	 */
	public static String encrypt(String xmlStr) {
		byte[] encrypt = null;

		try {
			// 取需要加密内容的utf-8编码。
			encrypt = xmlStr.getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// 取MD5Hash码,并组合加密数组
		byte[] md5Hasn = null;
		try {
			md5Hasn = EncryptUtil.MD5Hash(encrypt, 0, encrypt.length);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 组合消息体
		byte[] totalByte = EncryptUtil.addMD5(md5Hasn, encrypt);

		// 取密钥和偏转向量
		byte[] key = new byte[8];
		byte[] iv = new byte[8];
		getKeyIV(EncryptUtil.key, key, iv);
		SecretKeySpec deskey = new SecretKeySpec(key, "DES");
		IvParameterSpec ivParam = new IvParameterSpec(iv);

		// 使用DES算法使用加密消息体
		byte[] temp = null;
		try {
			temp = EncryptUtil.DES_CBC_Encrypt(totalByte, deskey, ivParam);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 使用Base64加密后返回
		return new BASE64Encoder().encode(temp);
	}

	/**
	 * <pre>
	 * 解密方法
	 * @param xmlStr  需要解密的消息字符串
	 * @return 解密后的字符串
	 * </pre>
	 */
	public static String decrypt(String xmlStr) throws Exception {
		// base64解码
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] encBuf = null;
		try {
			encBuf = decoder.decodeBuffer(xmlStr);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 取密钥和偏转向量
		byte[] key = new byte[8];
		byte[] iv = new byte[8];
		getKeyIV(EncryptUtil.key, key, iv);

		SecretKeySpec deskey = new SecretKeySpec(key, "DES");
		IvParameterSpec ivParam = new IvParameterSpec(iv);

		// 使用DES算法解密
		byte[] temp = null;
		try {
			temp = EncryptUtil.DES_CBC_Decrypt(encBuf, deskey, ivParam);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 进行解密后的md5Hash校验
		byte[] md5Hash = null;
		try {
			md5Hash = EncryptUtil.MD5Hash(temp, 16, temp.length - 16);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 进行解密校检
		for (int i = 0; i < md5Hash.length; i++) {
			if (md5Hash[i] != temp[i]) {
				// System.out.println(md5Hash[i] + "MD5校验错误。" + temp[i]);
				throw new Exception("MD5校验错误。");
			}
		}

		// 返回解密后的数组,其中前16位MD5Hash码要除去。
		return new String(temp, 16, temp.length - 16, "utf-8");
	}

	/**
	 * <pre>
	 * 经过封装的三重DES/CBC加密算法,如果包含中文,请注意编码。
	 * 
	 * @param sourceBuf 需要加密内容的字节数组。
	 * @param deskey     KEY 由24位字节数组通过SecretKeySpec类转换而成。
	 * @param ivParam    IV偏转向量,由8位字节数组通过IvParameterSpec类转换而成。
	 * @return 加密后的字节数组
	 * </pre>
	 */
	public static byte[] TripleDES_CBC_Encrypt(byte[] sourceBuf,
			SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
		byte[] cipherByte;
		// 使用DES对称加密算法的CBC模式加密
		Cipher encrypt = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");

		encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);

		cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);
		// 返回加密后的字节数组
		return cipherByte;
	}

	/**
	 * 
	 * <pre>
	 * 经过封装的三重DES / CBC解密算法
	 * @param sourceBuf    需要解密内容的字节数组
	 * @param deskey     KEY 由24位字节数组通过SecretKeySpec类转换而成。
	 * @param ivParam   IV偏转向量,由6位字节数组通过IvParameterSpec类转换而成。
	 * @return 解密后的字节数组
	 * </pre>
	 */
	public static byte[] TripleDES_CBC_Decrypt(byte[] sourceBuf,
			SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {

		byte[] cipherByte;
		// 获得Cipher实例,使用CBC模式。
		Cipher decrypt = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");
		// 初始化加密实例,定义为解密功能,并传入密钥,偏转向量
		decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);

		cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);
		// 返回解密后的字节数组
		return cipherByte;
	}

	/**
	 * <pre>
	 * 经过封装的DES/CBC加密算法,如果包含中文,请注意编码。
	 * 
	 * @param sourceBuf    需要加密内容的字节数组。
	 * @param deskey      KEY 由8位字节数组通过SecretKeySpec类转换而成。
	 * @param ivParam    IV偏转向量,由8位字节数组通过IvParameterSpec类转换而成。
	 * @return 加密后的字节数组
	 * </pre>
	 */
	public static byte[] DES_CBC_Encrypt(byte[] sourceBuf,
			SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
		byte[] cipherByte;
		// 使用DES对称加密算法的CBC模式加密
		Cipher encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");

		encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);

		cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);
		// 返回加密后的字节数组
		return cipherByte;
	}

	/**
	 * <pre>
	 * 经过封装的DES/CBC解密算法。
	 * 
	 * @param sourceBuf     需要解密内容的字节数组
	 * @param deskey       KEY 由8位字节数组通过SecretKeySpec类转换而成。
	 * @param ivParam     IV偏转向量,由6位字节数组通过IvParameterSpec类转换而成。
	 * @return 解密后的字节数组
	 * </pre>
	 */
	public static byte[] DES_CBC_Decrypt(byte[] sourceBuf,
			SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {

		byte[] cipherByte;
		// 获得Cipher实例,使用CBC模式。
		Cipher decrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
		// 初始化加密实例,定义为解密功能,并传入密钥,偏转向量
		decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);

		cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);
		// 返回解密后的字节数组
		return cipherByte;
	}

	/**
	 * <pre>
	 * MD5,进行了简单的封装,以适用于加,解密字符串的校验。
	 * 
	 * @param buf       需要MD5加密字节数组。
	 * @param offset    加密数据起始位置。
	 * @param length    需要加密的数组长度。
	 * </pre>
	 */
	public static byte[] MD5Hash(byte[] buf, int offset, int length)
			throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(buf, offset, length);
		return md.digest();
	}

	/**
	 * <pre>
	 * 字节数组转换为二行制表示
	 * 
	 * @param inStr   需要转换字节数组。
	 * @return 字节数组的二进制表示。
	 * </pre>
	 */
	public static String byte2hex(byte[] inStr) {
		String stmp;
		StringBuffer out = new StringBuffer(inStr.length * 2);

		for (int n = 0; n < inStr.length; n++) {
			// 字节做"与"运算,去除高位置字节 11111111
			stmp = Integer.toHexString(inStr[n] & 0xFF);
			if (stmp.length() == 1) {
				// 如果是0至F的单位字符串,则添加0
				out.append("0" + stmp);
			} else {
				out.append(stmp);
			}
		}
		return out.toString();
	}

	/**
	 * <pre>
	 * MD校验码 组合方法,前16位放MD5Hash码。 把MD5验证码byte[],加密内容byte[]组合的方法。
	 * 
	 * @param md5Byte     加密内容的MD5Hash字节数组。
	 * @param bodyByte    加密内容字节数组
	 * @return 组合后的字节数组,比加密内容长16个字节。
	 * </pre>
	 */
	public static byte[] addMD5(byte[] md5Byte, byte[] bodyByte) {
		int length = bodyByte.length + md5Byte.length;
		byte[] resutlByte = new byte[length];

		// 前16位放MD5Hash码
		for (int i = 0; i < length; i++) {
			if (i < md5Byte.length) {
				resutlByte[i] = md5Byte[i];
			} else {
				resutlByte[i] = bodyByte[i - md5Byte.length];
			}
		}

		return resutlByte;
	}

	/**
	 * <li>
	 * 方法名称:getKeyIV</li> <li>
	 * 功能描述:
	 * 
	 * <pre>
	 * 
	 * </pre>
	 * </li>
	 * 
	 * @param encryptKey
	 * @param key
	 * @param iv
	 */
	public static void getKeyIV(String encryptKey, byte[] key, byte[] iv) {
		// 密钥Base64解密
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] buf = null;
		try {
			buf = decoder.decodeBuffer(encryptKey);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 前8位为key
		int i;
		for (i = 0; i < key.length; i++) {
			key[i] = buf[i];
		}
		// 后8位为iv向量
		for (i = 0; i < iv.length; i++) {
			iv[i] = buf[i + 8];
		}
	}
	
}

 

分享到:
评论

相关推荐

    java类加密工具v2.1

    本工具是对java class文件进行加密保护防止反编译的工具!本工具全面支持linux/unix/windows操作系统。 继推出v1.0版本后,获得了用户大量的支持与的反馈,我们再次推出本v2.0版,对加密算法进行了更大的改进,安全...

    Java类加密工具v2.2(免注册)

    本工具是对java class文件进行加密保护防止反编译的工具!本工具全面支持linux/unix/windows操作系统。 继推出v1.0版本后,获得了用户大量的支持与的反馈,我们再次推出本v2.0版,对加密算法进行了更大的改进,安全...

    java常用工具类的使用

    在Java开发类库中,提供了很多工具类,我们即将学习最常见的工具类,比如对日期的操作,对集合的操作等。具体更多的工具类,请参考JavaDoc文档。 2. java.util.Date类 Date类包装了毫秒值,毫秒值表示自1970年1月1...

    AES加密解密 java实现

    用java实现的AES加密解密 内含AES工具包,提供了加密为16进制,和加密为字符两种。

    xml加密解密工具XMLEncryption

    xml加密(XML Encryption)是w3c加密xml的标准。...不管xml加密是如何完成的,保存加密数据总是用两种方法之一。 1、加密后所有的元素都被命名为 2、加密后只有数据被替换,而元素名称仍然是可读的,不会发生变化。

    JAVA_API1.6文档(中文)

    java.util 包含 collection 框架、遗留的 collection 类、事件模型、日期和时间设施、国际化和各种实用工具类(字符串标记生成器、随机数生成器和位数组)。 java.util.concurrent 在并发编程中很常用的实用工具类...

    Java 1.6 API 中文 New

    java.util 包含 collection 框架、遗留的 collection 类、事件模型、日期和时间设施、国际化和各种实用工具类(字符串标记生成器、随机数生成器和位数组)。 java.util.concurrent 在并发编程中很常用的实用工具类。...

    java源码包---java 源码 大量 实例

     WDSsoft的一款免费源代码 JCT 1.0,它是一个Java加密解密常用工具包。 Java局域网通信——飞鸽传书源代码 28个目标文件 内容索引:JAVA源码,媒体网络,飞鸽传书  Java局域网通信——飞鸽传书源代码,大家都知道VB...

    java api最新7.0

    java.util 包含 collection 框架、遗留的 collection 类、事件模型、日期和时间设施、国际化和各种实用工具类(字符串标记生成器、随机数生成器和位数组)。 java.util.concurrent 在并发编程中很常用的实用工具类。...

    JAVA上百实例源码以及开源项目

     WDSsoft的一款免费源代码 JCT 1.0,它是一个Java加密解密常用工具包。 Java局域网通信——飞鸽传书源代码 28个目标文件 内容索引:JAVA源码,媒体网络,飞鸽传书  Java局域网通信——飞鸽传书源代码,大家都知道VB...

    JAVA上百实例源码以及开源项目源代码

     WDSsoft的一款免费源代码 JCT 1.0,它是一个Java加密解密常用工具包。 Java局域网通信——飞鸽传书源代码 28个目标文件 内容索引:JAVA源码,媒体网络,飞鸽传书  Java局域网通信——飞鸽传书源代码,大家都知道VB...

    JavaAPI1.6中文chm文档 part1

    java.util 包含 collection 框架、遗留的 collection 类、事件模型、日期和时间设施、国际化和各种实用工具类(字符串标记生成器、随机数生成器和位数组)。 java.util.concurrent 在并发编程中很常用的实用工具类...

    java源码包4

     WDSsoft的一款免费源代码 JCT 1.0,它是一个Java加密解密常用工具包。 Java局域网通信——飞鸽传书源代码 28个目标文件 内容索引:JAVA源码,媒体网络,飞鸽传书  Java局域网通信——飞鸽传书源代码,大家都知道...

    java源码包3

     WDSsoft的一款免费源代码 JCT 1.0,它是一个Java加密解密常用工具包。 Java局域网通信——飞鸽传书源代码 28个目标文件 内容索引:JAVA源码,媒体网络,飞鸽传书  Java局域网通信——飞鸽传书源代码,大家都知道...

    MD5Utils.java

    md5工具类,里面有两种加密方法,encrypt,可以进去两个参数,里面有main方法,方便调试。

    java 反编译工具

    先我们来看看Java程序的反加密,也就是通常所说的Crack过程,只有明白了这个过程,我们才能有效的对我们的程序进行加密。 通常我们得到的Java程序的Crack包有两种,一种属于KeyGen(注册码生成器)、一种属于替换...

    java开源包11

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包6

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包9

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

Global site tag (gtag.js) - Google Analytics