RSA公私钥加解密方式-工具类
直接上代码
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.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 javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
/*** @author yao* @create 2018/1/20*/
public class RSAEncrypt {private static final String ALGORITHM = "RSA";private static final int MAX_ENCRYPT_BLOCK = 117;private static final int MAX_DECRYPT_BLOCK = 128;private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥public static final Integer PUBLICKEY = 0;//0表示公钥public static final Integer PRIVATEKEY = 1;//1表示私钥public RSAEncrypt() {}/*** 公钥加密* @param str 明文参数* @param publicKey 公钥* @return* @throws Exception*/public static String encryptPublic(String str, String publicKey) throws Exception {byte[] decoded = Base64.decodeBase64(publicKey);RSAPublicKey pubKey = (RSAPublicKey)KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));Cipher cipher = getCipher(1, pubKey);return splitEncrypt(str, cipher, pubKey.getModulus());}/*** 私钥加密* @param str 明文参数* @param privateKey 私钥* @return* @throws Exception*/public static String encryptPrivate(String str, String privateKey) throws Exception {byte[] decoded = Base64.decodeBase64(privateKey);RSAPrivateKey priKey = (RSAPrivateKey)KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));Cipher cipher = getCipher(1, priKey);return splitEncrypt(str, cipher, priKey.getModulus());}/*** 公钥解密* @param str 密文参数* @param publicKey 公钥* @return* @throws Exception*/public static String decryptPublic(String str, String publicKey) throws Exception {byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));byte[] decoded = Base64.decodeBase64(publicKey);RSAPublicKey pubKey = (RSAPublicKey)KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));Cipher cipher = getCipher(2, pubKey);return splitDecrypt(str, cipher, pubKey.getModulus());}/*** 私钥解密* @param str 密文参数* @param privateKey 私钥* @return* @throws Exception*/public static String decryptPrivate(String str, String privateKey) throws Exception {byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));byte[] decoded = Base64.decodeBase64(privateKey);RSAPrivateKey priKey = (RSAPrivateKey)KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));Cipher cipher = getCipher(2, priKey);return splitDecrypt(str, cipher, priKey.getModulus());}private static String splitDecrypt(String str, Cipher cipher, BigInteger modulus) throws Exception {byte[] bytes = Base64.decodeBase64(str);int inputLen = bytes.length;int offLen = 0;int i = 0;ByteArrayOutputStream byteArrayOutputStream;byte[] cache;for(byteArrayOutputStream = new ByteArrayOutputStream(); inputLen - offLen > 0; offLen = 128 * i) {if (inputLen - offLen > 128) {cache = cipher.doFinal(bytes, offLen, 128);} else {cache = cipher.doFinal(bytes, offLen, inputLen - offLen);}byteArrayOutputStream.write(cache);++i;}byteArrayOutputStream.close();cache = byteArrayOutputStream.toByteArray();return new String(cache);}private static Cipher getCipher(int model, Key key) throws Exception {Cipher cipher = Cipher.getInstance("RSA");cipher.init(model, key);return cipher;}private static String splitEncrypt(String str, Cipher cipher, BigInteger modulus) throws Exception {byte[] bytes = str.getBytes();int inputLen = bytes.length;int offLen = 0;int i = 0;ByteArrayOutputStream bops;byte[] cache;for(bops = new ByteArrayOutputStream(); inputLen - offLen > 0; offLen = 117 * i) {if (inputLen - offLen > 117) {cache = cipher.doFinal(bytes, offLen, 117);} else {cache = cipher.doFinal(bytes, offLen, inputLen - offLen);}bops.write(cache);++i;}bops.close();cache = bops.toByteArray();String encodeToString = Base64.encodeBase64String(cache);return encodeToString;}/*** 随机生成密钥对* @throws NoSuchAlgorithmException*/public static void genKeyPair() throws NoSuchAlgorithmException {// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");// 初始化密钥对生成器,密钥大小为96-1024位keyPairGen.initialize(1024,new SecureRandom());// 生成一个密钥对,保存在keyPair中KeyPair keyPair = keyPairGen.generateKeyPair();RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));// 得到私钥字符串String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));// 将公钥和私钥保存到MapkeyMap.put(PUBLICKEY ,publicKeyString); keyMap.put(PRIVATEKEY ,privateKeyString); }public static void main(String[] args) throws Exception {//参数String str = "{\"test\":\"001\"}";System.out.println("参数:" + str);//随机生成密钥对genKeyPair();//公钥加密System.out.println("公钥:" + keyMap.get(PUBLICKEY));System.out.println("私钥:" + keyMap.get(PRIVATEKEY));String encrypt = RSAEncrypt.encryptPublic(str, keyMap.get(PUBLICKEY));System.out.println("公钥加密:" + encrypt);//私钥解密String decrypt = RSAEncrypt.decryptPrivate(encrypt, keyMap.get(PRIVATEKEY));System.out.println("私钥解密:" + decrypt);//私钥加密String encryptPrivate = RSAEncrypt.encryptPrivate(str, keyMap.get(PRIVATEKEY));System.out.println("私钥加密:" + encryptPrivate);//公钥解密String decryptPublic = RSAEncrypt.decryptPublic(encryptPrivate, keyMap.get(PUBLICKEY));System.out.println("公钥解密:" + decryptPublic);}
}
RSA公私钥加解密方式-工具类相关推荐
- openssl_sign() 语法+RSA公私钥加密解密,非对称加密算法详解
其实有时候觉得写博客好烦,就个函数就开篇博客.很小的意见事情而已,知道的人看来多取一举,或者说没什么必要,浪费时间,不知道的人就会很郁闷.技术就是这样的,懂的人觉得真的很简单啊,不知道的人真的好难.. ...
- php RSA公钥私钥加解密和验证用法
现在很多项目中会使用到rsa加解密和验证相关的技术,分别整理代码如下,方便记忆和使用. [签名和验证] 1 //获得签名 2 function getSign($data) { 3 $pem = 'm ...
- java中使用openssl生成的rsa公私钥进行数据加解密_使用openssl生成RSA公钥和私钥对...
在ubuntu上要使用openssl的话需要先进行安装,命令如下: sudo apt-get install openssl 安装完成就可以使用openssl了. 首先需要进入openssl的交互界面 ...
- 基于RSA和AES混合加密实现的加解密小工具
基于RSA和AES混合加密实现的加解密小工具 闲来无事,用python的tkinter开发了一个基于RSA和AES混合加密的小小工具.总结一下使用到的知识点. 首先是核心的加解密部分. 采用混合加密的 ...
- MD5加盐加密工具类(可直接使用)
MD5加盐加密工具类 在我们做项目时,涉及到用户密码,而正常来说数据库中不会直接存储明文的密码,都是加密之后的密码. 密码加密的方式有很多,比如: ① 3DES.AES.DES:使用对称加密算法,可以 ...
- RSA公私钥格式分析及其在Java和Openssl之间的转换方法
文章目录 PKCS#1和PKCS#8 X.509公钥证书 ASN.1抽象语法标记 DER和PEM编码 OID对象标识符 用openssl命令生成PKCS1#格式的RSA密钥对 生成私钥 从私钥中导出公 ...
- Java(111):非对称加密RSA的使用(openssl生成RSA公私钥对)
Java(111):非对称加密RSA的使用(openssl生成RSA公私钥对) 1.openssl生成RSA公私钥对 [root@loaclhost ~]# openssl version OpenS ...
- 使用Java代码生成RSA公私钥的.pem文件
大家好,我是神韵,是一个技术&生活博主.出文章目的主要是两个,一是好记忆不如烂笔头,记录总结中提高自己.二是希望我的文章可以帮到大家.欢迎大家留言讨论,你们的行动将是我无限的动力. 本篇主题是 ...
- Cryptography,一个C#写的加解密算法的类
一个加解密算法的类,如下: Code using System; using System.IO; using System.Security.Cryptography; using System.T ...
最新文章
- 两款扁平步进电机及其驱动器VSMD102
- python使用手册-python 教程与手册(60IN1合集)
- Spring之Bean的配置(一)
- MvvmLight学习心得三
- Node.js Electron的扩展模块
- UVA 12108 Extraordinarily Tired Students
- python调用另一个.py文件中的类和函数
- 功夫小子实践开发-基本工具类的分析和实现
- Delphi XE 操作sqlite数据库
- 暨南大学人文社科a类期刊_暨南大学A类期刊目录.pdf
- Windows下 使用Python 3 调用讯飞 TTS 引擎实现文本转语音
- 基于微信小程序的校友录系统毕业设计源码
- 编写简单的计算器功能的程序
- 2020-05-13
- IIC总线协议---以存储芯片at24c64为例
- webpack多环境(dev stg prd qa)打包问题 1
- python:编解码器基类之增量式的编码和解码
- Guice + Jersey + Jetty 框架 - 学习笔记
- 计算机管理看板方式,Kanban|看板-现场管理-太友科技专业提供现场可视化整体解决方案...
- 【数据架构】什么是运营报告?
热门文章
- UCScript——C++集成脚本
- Dos下命令运行带有包名的Java类
- LINQ是死是活?——很奇怪为什么会有这样的话题?
- [Java基础][Java]toString()方法
- [剑指offer]面试题第[60]题[JAVA][n个骰子的点数][动态规划][空间优化]
- matlab如何找出最小的数据,读取数据并找出全部数据的最大值和最小值
- 职业中专计算机基础试讲课,职业中专计算机基础教育分析
- 计算机怎样辅助英语听力教学方法有哪些,计算机辅助教学在英语听力中的运用.doc...
- 653B. Bear and Compressing
- linux C之access函数