AES、DES 加密、解密

系统默认支持128位加密, 超过128位(如:192、256位),需要修改jdk系统默认限制,具体操作参考

http://blog.itpub.net/23071790/viewspace-723489/

使用AES加密时,当密钥大于128时,代码会抛出java.security.InvalidKeyException: Illegal key size or default parameters

Illegal key size or default parameters是指密钥长度是受限制的,java运行时环境读到的是受限的policy文件。文件位于${java_home}/jre/lib/security

这种限制是因为美国对软件出口的控制。

解决办法:

去掉这种限制需要下载Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.网址如下。

下载包的readme.txt 有安装说明。就是替换${java_home}/jre/lib/security/ 下面的local_policy.jar和US_export_policy.jar

jdk1.5: http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-plat-419418.html#jce_policy-1.5.0-oth-JPR

jdk1.6: http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

jdk1.7:http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

jdk1.8:http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

 

AES加密、解密

 

package com.lw.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;


public class EncryptUtil_AES {

	private static final String UTF_8 = "utf-8";
	private static final String AES = "AES";
	
	static String SECRET_PWD = "";

	static {
		// 获取密钥
		try {
			String str = "1234567890abcdef";
			byte[] b = str.getBytes(UTF_8);
			SECRET_PWD = new String(new Base64().encode(b));
			System.out.println("加密后的密钥:" + SECRET_PWD);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * AES加密
	 * <p>返回 Base64 加密结果 code</p>
	 * @param content 待加密的内容
	 * @return 加密后的base 64 code
	 * @throws Exception
	 */
	public static String encrypt(String content) {
		try {
			// 用AES算法加密的密钥
			SecretKeySpec key = getKey();
			// 对加密内容进行编码,并转化为字节数组
			byte[] byteContent = content.getBytes(UTF_8);
			// 创建密码器
			Cipher cipher = Cipher.getInstance(AES);
			// 以加密的方式用密钥初始化此 Cipher
			cipher.init(Cipher.ENCRYPT_MODE, key);
			// 加密算法对象对明文字节数组进行加密
			byte[] byteEncrypt = cipher.doFinal(byteContent);
			// 对加密结果进行Base64在加密后返回
			return base64Encode(byteEncrypt);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (InvalidKeyException e) {
			e.printStackTrace();
			return null;
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
			return null;
		} catch (BadPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * AES解密
	 * <p>Base64结果解密 </p>
	 * @param content 待解密的base 64 code
	 * @return 解密后的string
	 * @throws Exception
	 */
	public static String decrypt(String content) {
		try {
			// 用AES算法加密的密钥
			SecretKeySpec key = getKey();
			// 对加密内容先进行Base64解密
			byte[] byteContent = base64Decode(content);
			// 创建密码器
			Cipher cipher = Cipher.getInstance(AES);
			// 以加密的方式用密钥初始化此 Cipher
			cipher.init(Cipher.DECRYPT_MODE, key);
			// 加密算法对象对加密内容字节数组进行解密
			byte[] byteDecrypt = cipher.doFinal(byteContent);
			return new String(byteDecrypt);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
			return null;
		} catch (BadPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		} catch (InvalidKeyException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 生成密钥
	 * 
	 * @return SecretKeySpec 用AES算法加密的密钥
	 * @throws NoSuchAlgorithmException 
	 */
	public static SecretKeySpec getKey() throws NoSuchAlgorithmException {
		//实例化一个用AES加密算法的密钥生成器
		KeyGenerator kgen = KeyGenerator.getInstance(AES);
		//使用用户提供的密钥明文(SECRET_PWD)初始化此密钥生成器,使其具有确定的密钥大小128字节长
		kgen.init(128, new SecureRandom(SECRET_PWD.getBytes()));

		//生成一个密钥
		SecretKey secretKey = kgen.generateKey();
		//返回基本编码格式的密钥,如果此密钥不支持编码,则返回 null
		byte[] enCodeFormat = secretKey.getEncoded();
		//根据给定的enCodeFormat字节数组构造一个用AES算法加密的密钥
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);
		return key;
	}

	/**
	 * base 64 encode
	 * 
	 * @param bytes
	 *            待编码的byte[]
	 * @return 编码后的base 64 code
	 */
	public static String base64Encode(byte[] bytes) {
		return new String(new Base64().encode(bytes));
	}

	/**
	 * base 64 decode
	 * 
	 * @param base64Code
	 *            待解码的base 64 code
	 * @return 解码后的byte[]
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	public static byte[] base64Decode(String base64Code) throws UnsupportedEncodingException {
		return StringUtil.isEmpty(base64Code) ? null : new Base64().decode(base64Code.getBytes(UTF_8));
	}

}

 

 

DES加密、解密

 

package com.lw.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;


/**
 * 加密常用类
 * 使用org.apache.commons.codec.binary.Base64
 * @date 2016-04-15
 * @author liwei
 */
public class EncryptUtil_DES {
	
	private static final String TRIPLE_DES_CBC_PKCS5PADDING = "TripleDES/CBC/PKCS5Padding";
	private static final String UTF_8 = "utf-8";
	private static final String DES_CBC_PKCS5PADDING = "DES/CBC/PKCS5Padding";
	private static final String DES = "DES";
	// 密钥是16位长度的byte[]进行Base64转换后得到的字符串
	static String SECRET_PWD = "";

	static {
		// 获取密钥
		try {
			String str = "1234567890abcdef";
			byte[] b = str.getBytes(UTF_8);
			SECRET_PWD = new String(new Base64().encode(b));
			System.out.println("加密后的密钥:" + SECRET_PWD);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <b>加密方法</b> <li>方法名称:encrypt</li>
	 * 
	 * @param str
	 *            需要加密的消息字符串
	 * @return 加密后的字符串
	 */
	public static String encrypt(String str) {
		try {
			// 取需要加密内容的utf-8编码。
			byte[] encrypt = str.getBytes(UTF_8);
			// 取MD5Hash码,并组合加密数组
			byte[] md5Hasn = EncryptUtil_DES.MD5Hash(encrypt, 0, encrypt.length);
			// 组合消息体
			byte[] totalByte = EncryptUtil_DES.addMD5(md5Hasn, encrypt);

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

			// 使用DES算法使用加密消息体
			byte[] temp = EncryptUtil_DES.DES_CBC_Encrypt(totalByte, deskey, ivParam);

			// 使用Base64加密后返回
			return new String(new Base64().encode(temp));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (InvalidKeyException e) {
			e.printStackTrace();
			return null;
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
			return null;
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
			return null;
		} catch (BadPaddingException e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * <b>解密方法</b> <li>方法名称:encrypt</li>
	 * 
	 * @param str
	 *            需要解密的消息字符串
	 * @return 解密后的字符串
	 * @throws Exception
	 */
	public static String decrypt(String str) {
		try {
			// base64解码
			Base64 decoder = new Base64();
			byte[] encBuf = decoder.decode(str.getBytes());

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

			// 使用DES算法解密
			byte[] temp = EncryptUtil_DES.DES_CBC_Decrypt(encBuf, deskey, ivParam);

			// 进行解密后的md5Hash校验
			byte[] md5Hash = EncryptUtil_DES.MD5Hash(temp, 16, temp.length - 16);

			// 进行解密校检
			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校验错误。");
					return null;
				}
			}

			// 返回解密后的数组,其中前16位MD5Hash码要除去。
			return new String(temp, 16, temp.length - 16, UTF_8);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
			return null;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
			return null;
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
			return null;
		} catch (BadPaddingException e) {
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * <li>方法名称:DES_CBC_Encrypt</li>
	 * <li>功能描述:
	 * <pre>经过封装的DES/CBC加密算法,如果包含中文,请注意编码。</pre>
	 * </li>
	 * 
	 * @param sourceBuf
	 *            需要加密内容的字节数组。
	 * @param deskey
	 *            KEY 由8位字节数组通过SecretKeySpec类转换而成。
	 * @param ivParam
	 *            IV偏转向量,由8位字节数组通过IvParameterSpec类转换而成。
	 * @return 加密后的字节数组
	 * @throws NoSuchPaddingException 
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidAlgorithmParameterException 
	 * @throws InvalidKeyException 
	 * @throws BadPaddingException 
	 * @throws IllegalBlockSizeException 
	 * @throws Exception
	 */
	public static byte[] DES_CBC_Encrypt(byte[] sourceBuf, SecretKeySpec deskey, IvParameterSpec ivParam)
			throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
			InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		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;
	}

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

		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;
	}

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

	/**
	 * <li>方法名称:byte2hex</li>
	 * <li>功能描述:
	 * <pre>字节数组转换为二行制表示</pre>
	 * </li>
	 * 
	 * @param inStr
	 *            需要转换字节数组。
	 * @return 字节数组的二进制表示。
	 */
	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();
	}

	/**
	 * <li>方法名称:addMD5</li>
	 * <li>功能描述:
	 * <pre>MD校验码 组合方法,前16位放MD5Hash码。 把MD5验证码byte[],加密内容byte[]组合的方法。</pre>
	 * </li>
	 * 
	 * @param md5Byte
	 *            加密内容的MD5Hash字节数组。
	 * @param bodyByte
	 *            加密内容字节数组
	 * @return 组合后的字节数组,比加密内容长16个字节。
	 */
	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解密
		Base64 decoder = new Base64();
		byte[] buf = decoder.decode(encryptKey.getBytes());
		// 前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];
		}
	}

}

 

 

 

 

 

猜你喜欢

转载自davidhhs.iteye.com/blog/2292281