java处理RSA非对称加解密

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(698)   2023-03-28 11:29:14
java处理RSA非对称加解密
package org.xqlee.utils.security;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

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

/**
 * 
 * 
 * <pre>
 * _________________________INFO_____________________________
 * | Description : [RAS加密/解密工具类|其他说明,非对称加密速度非常慢,内容过大一般使用对称加密,然后对对称加密的密文进行非对称加密] 
 * | Encoding    : [UTF-8]
 * | Package     : [org.xqlee.utils.security]
 * | Project     : [utils]
 * | Author      : [LXQ]
 * | CreateDate  : []
 * | Updater     : []
 * | UpdateDate  : []
 * | UpdateRemark: []
 * | Company     : [www.zhljc.com]
 * | Version     : [v 1.0]
 * | Libs        : [commons-codec-1.x.jar]
 * __________________________________________________________
 * </pre>
 */
public class RSAUtil {
	/** 换行符 **/
	private final static String lineSeparator = System.getProperty("line.separator", "\n");
	/** 加解密算法键值-这里RSA **/
	private final static String KEY_ALGORITHM = "RSA";
	/** 获取公钥的KEY **/
	public final static String PUBLIC_KEY = "RSAPublicKey";
	/** 获取私钥的KEY **/
	public final static String PRIVATE_KEY = "RSAPrivateKey";

	/**
	 * 生成RSA算法的密钥对
	 * 
	 * @return 密钥对,Map-> key=RSAPublicKey|KEY=RSAPrivateKey
	 * @throws NoSuchAlgorithmException
	 *             获取密钥对可能发生的异常
	 */
	public static Map<String, Object> genKeyPair() throws NoSuchAlgorithmException {
		KeyPairGenerator kGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		// init the keyPair
		KeyPair keyPair = kGenerator.generateKeyPair();
		// get public key
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		// get private key
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		Map<String, Object> keys = new HashMap<String, Object>();
		keys.put(PUBLIC_KEY, publicKey);
		keys.put(PRIVATE_KEY, privateKey);
		return keys;
	}

	/**
	 * 加密
	 * 
	 * @param key
	 *            加密使用的[公钥/私钥]
	 * @param input
	 *            需要加密的明文
	 * @return 加密后的密文
	 * @throws Exception
	 *             加密过程中可能发生的异常
	 */
	public static byte[] encrypt(Key key, byte[] input) throws Exception {
		if (key != null) {
			// Cipher负责完成加密或解密工作,基于RSA
			Cipher cipher;
			try {
				cipher = Cipher.getInstance(KEY_ALGORITHM);
				// 根据公钥,对Cipher对象进行初始化
				cipher.init(Cipher.ENCRYPT_MODE, key);
				byte[] resultBytes = cipher.doFinal(input);
				return resultBytes;
			} catch (NoSuchAlgorithmException e) {
				throw new Exception("无此解密算法:" + e.getMessage());
			} catch (NoSuchPaddingException e) {
				throw new Exception("加密过程中发生异常:" + e.getMessage());
			} catch (InvalidKeyException e) {
				throw new Exception("解密私钥非法,请检查:" + e.getMessage());
			} catch (IllegalBlockSizeException e) {
				throw new Exception("密文长度非法:" + e.getMessage());
			} catch (BadPaddingException e) {
				throw new Exception("密文数据已损坏:" + e.getMessage());
			}

		} else {
			throw new Exception("解密私钥为空, 请设置");
		}
	}

	/**
	 * 解密
	 * 
	 * @param key
	 *            对应解密的[公钥或私钥]
	 * @param input
	 *            需要解密的加密信息
	 * @return 解密后的明文信息
	 * @throws Exception
	 *             解密过程中可能发生的异常
	 */
	public static byte[] decrypt(Key key, byte[] input) throws Exception {

		if (key == null) {
			throw new Exception("解密私钥为空, 请设置");
		}
		Cipher cipher = null;
		try {
			// Cipher负责完成加密或解密工作,基于RSA
			cipher = Cipher.getInstance(KEY_ALGORITHM);
			// 根据私钥,对Cipher对象进行初始化
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] output = cipher.doFinal(input);
			return output;
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此解密算法:" + e.getMessage());
		} catch (NoSuchPaddingException e) {
			throw new Exception("解密过程中发生异常:" + e.getMessage());
		} catch (InvalidKeyException e) {
			throw new Exception("解密私钥非法,请检查:" + e.getMessage());
		} catch (IllegalBlockSizeException e) {
			throw new Exception("密文长度非法:" + e.getMessage());
		} catch (BadPaddingException e) {
			throw new Exception("密文数据已损坏:" + e.getMessage());
		}

	}

	/**
	 * 通过文件获取私钥对象
	 * 
	 * @param file
	 *            私钥文件
	 * @return 私钥对象
	 * @throws Exception
	 *             从文件私钥获取私钥Java对象过程中可能发生的异常
	 */
	public static PrivateKey getPrivateKey(File file) throws Exception {
		String strPrivateKey = null;
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String readLine = null;
			StringBuilder sb = new StringBuilder();
			while ((readLine = br.readLine()) != null) {
				sb.append(readLine);
				sb.append(lineSeparator);
			}
			br.close();
			// 字符
			strPrivateKey = sb.toString().substring(0, sb.toString().length() - lineSeparator.length());

		} catch (IOException e) {
			throw new Exception("私钥数据流读取错误:" + e.getMessage());
		}

		try {
			byte[] buffer = Base64.decodeBase64(strPrivateKey.getBytes());
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			return keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("=====无此算法=====");
		} catch (InvalidKeySpecException e) {
			throw new Exception("=====密钥非法=====");
		} catch (NullPointerException e) {
			throw new Exception("=====私钥数据为空=====");
		}

	}

	/**
	 * 通过字符串获取私钥对象
	 * 
	 * @param strPrivateKey
	 *            字符串的私钥
	 * @return 私钥对象
	 * @throws Exception
	 *             从字符串私钥获取私钥Java对象过程中可能发生的异常
	 */
	public static PrivateKey getPrivateKey(String strPrivateKey) throws Exception {
		try {
			byte[] buffer = Base64.decodeBase64(strPrivateKey.getBytes());
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			return keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("=====无此算法=====");
		} catch (InvalidKeySpecException e) {
			throw new Exception("=====密钥非法=====");
		} catch (NullPointerException e) {
			throw new Exception("=====私钥数据为空=====");
		}

	}

	/**
	 * 从公钥文件中加载获取公钥Java对象
	 * 
	 * @param file
	 *            公钥文件
	 * @return Java公钥对象
	 * @throws Exception
	 *             获取过程中可能发生的异常
	 */
	public static PublicKey getPublicKey(File file) throws Exception {
		String strRSAPublicKey = null;
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String readLine = null;
			StringBuilder sb = new StringBuilder();
			while ((readLine = br.readLine()) != null) {
				sb.append(readLine);
				sb.append(lineSeparator);
			}
			br.close();
			strRSAPublicKey = sb.toString().substring(0, sb.toString().length() - lineSeparator.length());
		} catch (IOException e) {
			throw new Exception("公钥数据流读取错误");
		} catch (NullPointerException e) {
			throw new Exception("公钥输入流为空");
		}
		try {
			byte[] buffer = Base64.decodeBase64(strRSAPublicKey.getBytes());
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("=====无此算法=====");
		} catch (InvalidKeySpecException e) {
			throw new Exception("=====公钥非法=====");
		} catch (NullPointerException e) {
			throw new Exception("=====公钥数据为空=====");
		}

	}

	/**
	 * 从公钥字符串加载获取公钥Java对象
	 * 
	 * @param strPublicKey
	 *            公钥字符串
	 * @return Java公钥对象
	 * @throws Exception
	 *             获取过程中可能发生的异常
	 */
	public static PublicKey getPublicKey(String strPublicKey) throws Exception {
		try {
			byte[] buffer = Base64.decodeBase64(strPublicKey.getBytes());
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("=====无此算法=====");
		} catch (InvalidKeySpecException e) {
			throw new Exception("=====公钥非法=====");
		} catch (NullPointerException e) {
			throw new Exception("=====公钥数据为空=====");
		}

	}

	/**
	 * 将Java对象的公钥或者私钥转换为字符串
	 * 
	 * @param key
	 *            公钥/私钥
	 * @return 秘钥的字符串
	 */
	public static String key2String(Key key) {
		byte[] keyBytes = key.getEncoded();
		String result = new String(Base64.encodeBase64(keyBytes));
		return result;
	}
}
 
标签:
地址:https://www.leftso.com/article/16.html

相关阅读

Java生成密钥对采用hutool工具生KeyPair keyPair = SecureUtil.generateKeyPair("RSA"); PrivateKey aPrivate = k...
引言AES代表高级加密系统,它是一种对称加密算法
spring boot 入门之security oauth2 jwt完美整合例子,Java编程中spring boot框架+spring security框架+spring security o...
问题描述默认情况下,在使用spring的restTemplate调用接口,如果响应的http状态码是200则会成功返回数据
java c++通用DES加密算法(包含源代码),本来觉得DES、AES这种流行加密算法,使用起来应该很简单。但研究后发现有两个变数:1分块的方式。加密是逐块进行的。2.padding的方式。当...
学习使用Spring Batch分区使用多个线程来处理Spring Boot应用程序中的一系列数据集任务。1.并行处理和分区1.1 并行处理 大多数批处理问题可以使用单线程解决,但很少有复杂的场...
在Java编程中,ORM框架mybaties处理@Select注解中的动态sql处理方法
1. 线程的安全性问题:线程安全和非线程安全: 一个类在单线程环境下能够正常运行,并且在多线程环境下,使用方不做特别处理也能运行正常,我们就称其实线程安全的