1.随机生成密钥对

 /**
* 随机生成密钥对
* @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())));
// 将公钥和私钥保存到Map
//0表示公钥
keyMap.put(0,publicKeyString);
//1表示私钥
keyMap.put(1,privateKeyString);
}

2.RSA公钥加密

/**
* RSA公钥加密
* @param str 加密字符串
* @param publicKey 公钥
* @return 密文
* @throws Exception 加密过程中的异常信息
*
*/
public static String encrypt( String str, String publicKey ) throws Exception{
try {
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] strBytes = str.getBytes("UTF-8");
int inputLength = strBytes.length;
System.out.println("加密字节数:" + inputLength);
// 最大加密字节数,超出最大字节数需要分组加密
// 标识
int offSet = 0;
byte[] resultBytes = {};
byte[] cache;
while (inputLength - offSet > 0) {
if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(strBytes, offSet, MAX_ENCRYPT_BLOCK);
offSet += MAX_ENCRYPT_BLOCK;
} else {
cache = cipher.doFinal(strBytes, offSet, inputLength - offSet);
offSet = inputLength;
}
resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
}
String outStr = Base64.encodeBase64String(resultBytes);
return outStr;
}catch (Exception e){
System.out.println("rsaEncrypt error:" + e.getMessage());
}
return "";
}

3.RSA私钥解密

 /**
* RSA私钥解密
* @param str 加密字符串
* @param privateKey 私钥
* @return 铭文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int inputLen = inputByte.length;
System.out.println("解密字节数:" + inputLen);
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(inputByte, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(inputByte, offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
// 解密后的内容
String outStr = new String(decryptedData);
return outStr;
}

4.使用

   private static final Map<Integer,String> keyMap=new HashMap<>();

    /**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117; /**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;   /**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//生成公钥和私钥
genKeyPair();
//加密字符串
String message = "sdaw";
System.out.println("随机生成的公钥为:" + keyMap.get(0));
System.out.println("随机生成的私钥为:" + keyMap.get(1));
String messageEn = encrypt(message,keyMap.get(0));
System.out.println(message + "\t加密后的字符串为:" + messageEn);
String messageDe = decrypt(messageEn,keyMap.get(1));
System.out.println("还原后的字符串为:" + messageDe);
}

java RSA生成公钥和私钥的更多相关文章

  1. Java RSA 生成公钥 私钥

    目前为止,RSA是应用最多的公钥加密算法,能够抵抗已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准. RSA算法中,每个通信主体都有两个钥匙,一个公钥(Public Key)用来对数据进行加密 ...

  2. java RSA 生成公钥私钥

    /** * 引进的包都是Java自带的jar包 * 秘钥相关包 * base64 编解码 * 这里只用到了编码 */ import java.security.Key; import java.sec ...

  3. git 生成公钥、私钥方法与clone使用方法

    我的配置流程 Git配置 Git安装完之后,需做git配置.打开git bash,分别执行以下两句命令 git config --global user.name "用户名" gi ...

  4. RSA的公钥、私钥

    一.举个例子 1.发消息 用对方的公钥给对方发消息 2.发公告 发公告的时候,用自己的私钥形成签名! 二.加密和签名 RSA的公钥.私钥是互相对应的,RSA会生成两个密钥,你可以把任何一个用于公钥,然 ...

  5. Git简单生成生成公钥和私钥方法

    Git简单生成生成公钥和私钥方法 Git配置 Git安装完之后,需做最后一步配置.打开git bash,分别执行以下两句命令 git config --global user.name “用户名” g ...

  6. GIT生成公钥和私钥

    转载至:https://blog.csdn.net/gwz1196281550/article/details/80268200 打开 git bash! git config --global us ...

  7. Git安装与使用(windows环境)(一)----Git安装、生成公钥和私钥、添加SSH

    安装 1.从官网下载git:http://git-scm.com/downloads 2.安装git,选择git组件安装,如下图 3.一直next,直到出现下面的窗口.这里是选择命令行形式.(可以理解 ...

  8. 使用keytool生成公钥、私钥、证书并且读取出来,使用私钥签名jar并验证(转)

    参考链接:http://happyqing.iteye.com/blog/2139504 :https://blog.csdn.net/arjelarxfc/article/details/52461 ...

  9. openssl pem 生成公钥和私钥及文件

    openssl pem.h 中提供了关于pem格式密钥对的操作接口 通常使用.pem的格式文件来保存openssl 生成的密钥对: 在终端下 cat xxx.pem 可以看到 p.p1 { margi ...

  10. MAC下用OPENSSL生成公钥和私钥

    MAC OS自带了OpenSSL,所以不用去编译那一坨跟SHIT一样的源码.直接在命令行里使用OPENSSL就可以. 打开命令行工具,然后输入 openssl打开openssl,接着只要三句命令就可以 ...

随机推荐

  1. 【原创】android 7.0 通知报错 java.lang.SecurityException: You need MANAGE_USERS permission to: check if specified user a managed profile outside your profile group

    项目中在后台发送通知,突然某一天测出在Android 7.0上通知发送失败,那么根据提示,我们尝试加了MANAGE_USERS权限,看起来是个系统级别权限,验证后果然无效.接着在搜索后都无果,似乎大家 ...

  2. <a-upLoad>连报三错

    [Vue warn]: Invalid prop: custom validator check failed for prop "fileList". [Vue warn]: I ...

  3. 微信公众号授权登录,整合spring security

    公司的业务需求,对接了微信公众号授权,通过微信公众号的接口拿到用户信息进行业务系统的登录,话不多说上代码,我的实现方式是整合了spingSecurity 首先是接口 @PostMapping(&quo ...

  4. linux查看已知进程PID所在的目录

    pwdx 命令 pwdx PID [was@CMTRMWAS1 ~]$ pwdx 31996 31996: /was/AppServer/profiles/AppSrv03

  5. Centos7.6操作系统安装

    新建虚拟机 默认下一步 稍后安装操作系统 选择对应的操作系统和版本 指定虚拟机名称和存储位置 处理器配置 内存配置:图形化界面至少2G,字符界面至少1G. 网络类型默认为NAT I/O控制器类型默认L ...

  6. MasaFramework入门第二篇,安装MasaFramework了解各个模板

    安装MasaFramework模板 执行以下命令安装最新Masa的模板 dotnet new --install Masa.Template 安装完成将出现四个模板 Masa Blazor App: ...

  7. 开源不易、安全慎行,中国软件如何走向文明?丨RTE 技术环境月报 202205

    各位开发者小伙伴: 这里是 2022 年第 5 期的 RTE<技术环境月报>--致力于成为对大家"有用"的 Highlight 看板--每月初通过 RTC 开发者社区( ...

  8. Vditor在原生JS中如何结合后端使用

    目录 1.Vditor介绍 2.如何在原生JS中结合后端使用 2.1 背景 2.2 正确使用方式 2.2.1 编辑页面 2.2.2 回显页面(修改页面) 2.2.3 预览页面 3.小结一下 1.Vdi ...

  9. RPC通信原理概述

    RPC通信原理概述 1.RPC概述 1.什么是RPC RPC(Remote Procedure Call Protocol)远程过程调用协议.它是一种通过网络从远程计算机程序上请求服务,而不需要了解底 ...

  10. 设计模式(二十八)----综合应用-自定义Spring框架-Spring简单回顾

    1 spring使用回顾 自定义spring框架前,先回顾一下spring框架的使用,从而分析spring的核心,并对核心功能进行模拟. 数据访问层.定义UserDao接口及其子实现类 public ...