java 加密工具类(MD5、RSA、AES等加密方式)

本文详细介绍了多种加密算法,包括MD5、AES、Base64、DES、RSA等,提供了每种算法的实现代码,涵盖了对称加密、非对称加密及散列算法,适合信息安全、加密解密等领域学习。

 MD5加密

import org.apache.commons.codec.digest.DigestUtils;
 
/**
 * MD5加密组件
 * 
 * @version 1.0
 * @since 1.0
 */
public abstract class MD5Util {
 
	/**
	 * MD5加密
	 * 
	 * @param data
	 *            待加密数据
	 * @return byte[] 消息摘要
	 * 
	 * @throws Exception
	 */
	public static byte[] encodeMD5(String data) throws Exception {
 
		// 执行消息摘要
		return DigestUtils.md5(data);
	}
 
	/**
	 * MD5加密
	 * 
	 * @param data
	 *            待加密数据
	 * @return byte[] 消息摘要
	 * 
	 * @throws Exception
	 */
	public static String encodeMD5Hex(String data) {
		// 执行消息摘要
		return DigestUtils.md5Hex(data);
	}
}

AES加密和解密:


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
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 sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AESUtil {
	private static final String encryptEncodeRules = "rxxg";// 定义默认加密规则

	/**
	 * @param content
	 * @return string @Description: Aes加密流程: 1.构造密钥生成器 2.根据ecnodeRules规则初始化密钥生成器
	 *         3.产生密钥 4.创建和初始化密码器 * 5.内容加密 6.返回字符串
	 */
	public static String invokeEncryptEncode(String content) {
		String resultEncode = "";
		try {
			// [1].利用KeyGenerator构造密钥生成器,指定为AES算法,不区分大小写
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			// [2].根据encryptEncodeRules规则初始化密钥生成器,生成一个128位的随机源,根据传入的字节数组,实现随机数算法
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(encryptEncodeRules.getBytes());
			keyGenerator.init(128, random);
			// [3].产生原始对称密钥
			SecretKey originalKey = keyGenerator.generateKey();
			// [4].获得原始对称密钥的字节数组
			byte[] rawByte = originalKey.getEncoded();
			// [5].根据字节数组生成AES密钥
			SecretKey secretKey = new SecretKeySpec(rawByte, "AES");
			// [6].根据指定算法AES自成密码器
			Cipher cipher = Cipher.getInstance("AES");
			// [7].初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			// [8].获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
			byte[] byteEncode = content.getBytes("utf-8");
			// [9].根据密码器的初始化方式--加密:将数据加密
			byte[] bytesAes = cipher.doFinal(byteEncode);
			// [10].将加密后的数据转换为字符串
			// 这里用Base64Encoder中会找不到包
			// 解决办法:
			// 在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
			resultEncode = new String(new BASE64Encoder().encode(bytesAes));
			// [11].将字符串返回
			return resultEncode;
		} catch (NoSuchAlgorithmException exception) {
			exception.printStackTrace();
		} catch (NoSuchPaddingException exception) {
			exception.printStackTrace();
		} catch (InvalidKeyException exception) {
			exception.printStackTrace();
		} catch (UnsupportedEncodingException exception) {
			exception.printStackTrace();
		} catch (IllegalBlockSizeException exception) {
			exception.printStackTrace();
		} catch (BadPaddingException exception) {
			exception.printStackTrace();
		}
		return resultEncode;
	}

	/**
	 * @param content
	 * @return String @Description:解密流程: * 1.同加密1-4步 2.将加密后的字符串反纺成byte[]数组 3.将加密内容解密
	 */
	public static String invokeDecryptEncode(String content) {
		String resultEncode = "";
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(encryptEncodeRules.getBytes());
			keyGenerator.init(128, random);
			SecretKey originalKey = keyGenerator.generateKey();
			byte[] byteArray = originalKey.getEncoded();
			SecretKey secretKey = new SecretKeySpec(byteArray, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			// [7]将加密并编码后的内容解码成字节数组
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			// [8]解密密文
			byte[] byteContent = new BASE64Decoder().decodeBuffer(content);
			byte[] byteEncode = cipher.doFinal(byteContent);
			resultEncode = new String(byteEncode, "utf-8");
			return resultEncode;
		} catch (NoSuchAlgorithmException exception) {
			exception.printStackTrace();
		} catch (NoSuchPaddingException exception) {
			exception.printStackTrace();
		} catch (InvalidKeyException exception) {
			exception.printStackTrace();
		} catch (UnsupportedEncodingException exception) {
			exception.printStackTrace();
		} catch (IllegalBlockSizeException exception) {
			exception.printStackTrace();
		} catch (BadPaddingException exception) {
			exception.printStackTrace();
		} catch (IOException exception) {
			exception.printStackTrace();
		}
		return resultEncode;
	}

	public static void main(String[] args) {
		String[] keys = { "123456", "123abc" };
		System.out.println("测试加密:");
		for (String key : keys) {
			System.out.print("原始密文key:[" + key + "],");
			String encryptString = invokeEncryptEncode(key);
			System.out.print("加密encryptString:[" + encryptString + "],");
			String decryptString = invokeDecryptEncode(encryptString);
			System.out.println("解密decryptString:[" + decryptString + "]");
		}
	}

}

Base64加密:

    import org.apache.commons.codec.binary.Base64;
     
    /**
     * Base64组件
     *
     * @version 1.0
     * @since 1.0
     */
    public abstract class Base64Util {
     
    	/**
    	 * 字符编码
    	 */
    	public final static String ENCODING = "UTF-8";
     
    	/**
    	 * Base64编码
    	 * 
    	 * @param data 待编码数据
    	 * @return String 编码数据
    	 * @throws Exception
    	 */
    	public static String encode(String data) throws Exception {
     
    		// 执行编码
    		byte[] b = Base64.encodeBase64(data.getBytes(ENCODING));
     
    		return new String(b, ENCODING);
    	}
     
    	/**
    	 * Base64安全编码<br>
    	 * 遵循RFC 2045实现
    	 * 
    	 * @param data
    	 *            待编码数据
    	 * @return String 编码数据
    	 * 
    	 * @throws Exception
    	 */
    	public static String encodeSafe(String data) throws Exception {
     
    		// 执行编码
    		byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true);
     
    		return new String(b, ENCODING);
    	}
     
    	/**
    	 * Base64解码
    	 * 
    	 * @param data 待解码数据
    	 * @return String 解码数据
    	 * @throws Exception
    	 */
    	public static String decode(String data) throws Exception {
     
    		// 执行解码
    		byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));
     
    		return new String(b, ENCODING);
    	}
     
    }

DES加密:

import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
 
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
 
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
/**
 * DES安全编码组件
 * 
 * @version 1.0
 */
public abstract class DESUtil {
	static{
		Security.insertProviderAt(new BouncyCastleProvider(), 1);
	}
	/**
	 * 密钥算法 <br>
	 * Java 6 只支持56bit密钥 <br>
	 * Bouncy Castle 支持64bit密钥
	 */
	public static final String KEY_ALGORITHM = "DES";
 
	/**
	 * 加密/解密算法 / 工作模式 / 填充方式
	 */
	public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";
 
	/**
	 * 转换密钥
	 * 
	 * @param key
	 *            二进制密钥
	 * @return Key 密钥
	 * @throws Exception
	 */
	private static Key toKey(byte[] key) throws Exception {
 
		// 实例化DES密钥材料
		DESKeySpec dks = new DESKeySpec(key);
 
		// 实例化秘密密钥工厂
		SecretKeyFactory keyFactory = SecretKeyFactory
				.getInstance(KEY_ALGORITHM);
 
		// 生成秘密密钥
		SecretKey secretKey = keyFactory.generateSecret(dks);
 
		return secretKey;
	}
 
	/**
	 * 解密
	 * 
	 * @param data
	 *            待解密数据
	 * @param key
	 *            密钥
	 * @return byte[] 解密数据
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
 
		// 还原密钥
		Key k = toKey(key);
 
		// 实例化
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
 
		// 初始化,设置为解密模式
		cipher.init(Cipher.DECRYPT_MODE, k);
 
		// 执行操作
		return cipher.doFinal(data);
	}
 
	/**
	 * 加密
	 * 
	 * @param data
	 *            待加密数据
	 * @param key
	 *            密钥
	 * @return byte[] 加密数据
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
 
		// 还原密钥
		Key k = toKey(key);
 
		// 实例化
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
 
		// 初始化,设置为加密模式
		cipher.init(Cipher.ENCRYPT_MODE, k);
 
		// 执行操作
		return cipher.doFinal(data);
	}
 
	/**
	 * 生成密钥 <br>
	 * Java 6 只支持56bit密钥 <br>
	 * Bouncy Castle 支持64bit密钥 <br>
	 * 
	 * @return byte[] 二进制密钥
	 * @throws Exception
	 */
	public static byte[] initKey() throws Exception {
 
		/*
		 * 实例化密钥生成器
		 * 
		 * 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM);
		 * 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");
		 */
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
 
		/*
		 * 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64);
		 */
		kg.init(56, new SecureRandom());
 
		// 生成秘密密钥
		SecretKey secretKey = kg.generateKey();
 
		// 获得密钥的二进制编码形式
		return secretKey.getEncoded();
	}
	
	public static byte[] initKey(String seed) throws Exception {
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		SecureRandom secureRandom = new SecureRandom(new Base64().decode(seed));  
		kg.init(secureRandom);
		SecretKey secretKey = kg.generateKey();
		return secretKey.getEncoded();
	}
}

RSA加密:

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
 
import javax.crypto.Cipher;
 
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
 
 
/**
 * RSA安全编码组件
 * 
 * @version 1.0
 */
public class RSAUtil {
	/**
	 * 非对称加密密钥算法
	 */
	public static final String KEY_ALGORITHM_RSA = "RSA";
 
	/**
	 * 公钥
	 */
	private static final String RSA_PUBLIC_KEY = "RSAPublicKey";
 
	/**
	 * 私钥
	 */
	private static final String RSA_PRIVATE_KEY = "RSAPrivateKey";
	
	/**
	 * RSA密钥长度 
	 * 默认1024位,
	 * 密钥长度必须是64的倍数, 
	 * 范围在512至65536位之间。
	 */
	private static final int KEY_SIZE = 1024;
	
	static{
		Security.insertProviderAt(new BouncyCastleProvider(), 1);
	}
	/**
	 * 私钥解密
	 * 
	 * @param data
	 *            待解密数据
	 * @param key
	 *            私钥
	 * @return byte[] 解密数据
	 * @throws Exception
	 */
	public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
			throws Exception {
 
		// 取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
 
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
 
		// 生成私钥
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
 
		// 对数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
 
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
 
		int blockSize = cipher.getBlockSize();
		if(blockSize>0){
			ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
			int j = 0;
			while (data.length - j * blockSize > 0) {
				bout.write(cipher.doFinal(data, j * blockSize, blockSize));
				j++;
			}
			return bout.toByteArray();
		}
		return cipher.doFinal(data);
	}
 
	/**
	 * 公钥解密
	 * 
	 * @param data
	 *            待解密数据
	 * @param key
	 *            公钥
	 * @return byte[] 解密数据
	 * @throws Exception
	 */
	public static byte[] decryptByPublicKey(byte[] data, byte[] key)
			throws Exception {
 
		// 取得公钥
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
 
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
 
		// 生成公钥
		PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
 
		// 对数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
 
		cipher.init(Cipher.DECRYPT_MODE, publicKey);
 
		return cipher.doFinal(data);
	}
 
	/**
	 * 公钥加密
	 * 
	 * @param data
	 *            待加密数据
	 * @param key
	 *            公钥
	 * @return byte[] 加密数据
	 * @throws Exception
	 */
	public static byte[] encryptByPublicKey(byte[] data, byte[] key)
			throws Exception {
 
		// 取得公钥
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
 
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
		
		PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
 
		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
 
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		
		int blockSize = cipher.getBlockSize();
		if(blockSize>0){
			int outputSize = cipher.getOutputSize(data.length);
			int leavedSize = data.length % blockSize;
			int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
					: data.length / blockSize;
			byte[] raw = new byte[outputSize * blocksSize];
			int i = 0,remainSize=0;
			while ((remainSize = data.length - i * blockSize) > 0) {
				int inputLen = remainSize > blockSize?blockSize:remainSize;
				cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
				i++;
			}
			return raw;
		}
		return cipher.doFinal(data);
	}
 
	/**
	 * 私钥加密
	 * 
	 * @param data
	 *            待加密数据
	 * @param key
	 *            私钥
	 * @return byte[] 加密数据
	 * @throws Exception
	 */
	public static byte[] encryptByPrivateKey(byte[] data, byte[] key)
			throws Exception {
 
		// 取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
 
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
 
		// 生成私钥
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
 
		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
 
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
 
		int blockSize = cipher.getBlockSize();
		if(blockSize>0){
			int outputSize = cipher.getOutputSize(data.length);
			int leavedSize = data.length % blockSize;
			int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
					: data.length / blockSize;
			byte[] raw = new byte[outputSize * blocksSize];
			int i = 0,remainSize=0;
			while ((remainSize = data.length - i * blockSize) > 0) {
				int inputLen = remainSize > blockSize?blockSize:remainSize;
				cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
				i++;
			}
			return raw;
		}
		return cipher.doFinal(data);
	}
 
	/**
	 * 取得私钥
	 * 
	 * @param keyMap
	 *            密钥Map
	 * @return key 私钥
	 * @throws Exception
	 */
	public static Key getPrivateKey(Map<String, Key> keyMap)
			throws Exception {
		return keyMap.get(RSA_PRIVATE_KEY);
	}
 
	/**
	 * 取得私钥
	 * 
	 * @param keyMap
	 *            密钥Map
	 * @return byte[] 私钥
	 * @throws Exception
	 */
	public static byte[] getPrivateKeyByte(Map<String, Key> keyMap)
			throws Exception {
		return keyMap.get(RSA_PRIVATE_KEY).getEncoded();
	}
	
	/**
	 * 取得公钥
	 * 
	 * @param keyMap
	 *            密钥Map
	 * @return key 公钥
	 * @throws Exception
	 */
	public static Key getPublicKey(Map<String, Key> keyMap)
			throws Exception {
		return keyMap.get(RSA_PUBLIC_KEY);
	}
	
	/**
	 * 取得公钥
	 * 
	 * @param keyMap
	 *            密钥Map
	 * @return byte[] 公钥
	 * @throws Exception
	 */
	public static byte[] getPublicKeyByte(Map<String, Key> keyMap)
			throws Exception {
		return keyMap.get(RSA_PUBLIC_KEY).getEncoded();
	}
	
	/**
	 * 初始化密钥
	 * @param byte[] seed 种子
	 * @return Map 密钥Map
	 * @throws Exception
	 */
	public static Map<String,Key> initKey(byte[] seed)throws Exception{
		// 实例化密钥对生成器
		KeyPairGenerator keyPairGen = KeyPairGenerator
				.getInstance(KEY_ALGORITHM_RSA);
 
		// 初始化密钥对生成器
		keyPairGen.initialize(KEY_SIZE,	new SecureRandom(seed) );
 
		// 生成密钥对
		KeyPair keyPair = keyPairGen.generateKeyPair();
 
		// 公钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
 
		// 私钥
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
 
		// 封装密钥
		Map<String, Key> keyMap = new HashMap<String, Key>(2);
 
		keyMap.put(RSA_PUBLIC_KEY, publicKey);
		keyMap.put(RSA_PRIVATE_KEY, privateKey);
 
		return keyMap;
	}
	
	/**
	 * 初始化密钥
	 * @param seed 种子
	 * @return Map 密钥Map
	 * @throws Exception
	 */
	public static Map<String,Key> initKey(String seed)throws Exception{
		return initKey(seed.getBytes());
	}
 
	/**
	 * 初始化密钥
	 * 
	 * @return Map 密钥Map
	 * @throws Exception
	 */
	public static Map<String, Key> initKey() throws Exception {
		return initKey(UUID.randomUUID().toString().getBytes());
	}
	
	public static PublicKey getPublicRSAKey(String key) throws Exception {
		X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(key));
		KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
		return kf.generatePublic(x509);
	}
 
	public static PrivateKey getPrivateRSAKey(String key) throws Exception {
		PKCS8EncodedKeySpec pkgs8 = new PKCS8EncodedKeySpec(Base64.decode(key));
		KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
		return kf.generatePrivate(pkgs8);
	}
 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值