Java处理RSA非对称加解密

编程教程 > Java (1226) 2025-01-25 15:07:35

Java原生实现RSA非对称加加密,源码参考:

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;


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

 

over ,搞定收工!

 


评论
User Image
提示:请评论与当前内容相关的回复,广告、推广或无关内容将被删除。

相关文章
Java原生实现RSA非对称加加密,源码参考:import java.io.BufferedReader;import java.io.File;import
java c++通用DES加密算法(包含源代码),本来觉得DES、AES这种流行加密算法,使用起来应该很简单。但研究后发现有两个变数:1分块的方式。加密是逐块进行的。2.padding的方式。当...
Spring boot hessian 通讯加密,Spring boot hessian RPC框架通讯之间的加密验证。实现安全的RPC访问
java编程之java jwt token使用,autho0的Java-jwt框架使用,java编程,java-jwt
前言前面已经学习了Vert.x web的基础接口,本文主要讲解引入jwt为接口认证/鉴权。引用之前创建的项目《Vert.x 4 Web应用初识》,加入jwt t
spring boot 入门之security oauth2 jwt完美整合例子,Java编程中spring boot框架+spring security框架+spring security o...
Linux系统SSH命令基础用法,Linux,Linux系统
java语言MD5加密字符串,计算文件的MD5值package org.xqlee.utils.security;import java.io.File;imp
本文讲解什么是JWT,JWT的构成和JWT算法?,Java编程,JWT
jQuery之MD5加密插件使用及下载,网络中md5进行简单加密的地方越来越多。这里讲解一个jQuery的md5插件
tomcat如何配置SSL或者说HTTPS,tomcat,https,SSL。为何需要使用SSL
在这个Spring Boot示例中,学习将 Web 应用程序配置为使用自签名证书在 SSL (HTTPS) 上运行
Postman 请求前修改密码为MD5值Postman请求参数设置 选择Pre-request Script栏目 获取明文密码并md5加密后设置到变量中 脚本://获取明文密码 let pwd...
以下内容仅供学习研究使用切勿商业用途​​​​​​​以下操作仅以19.6版本为参考其他版本可能有所不同aspose-slides 主要用来PPT转图片/PPT转PDF 支持.ppt/.pptx
问题描述idea启动maven的JavaFX项目报错:Exception in Application start method java.lang.reflect.InvocationTarg...