当前位置: 首页 > news >正文

Java RSA密钥转换,从RSAPrivateKey得到RSAPublicKey

概述:

在Java编程中,我们经常用到如下一段代码来生成RSA公私钥,分别拿到公私钥然后加解密计算:

KeyPairGenerator keyPairGen;
keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

本文讲述仅有RSAPrivateKey privateKey,没有KeyPair keyPair,如何通过RSAPrivateKey privateKey得到RSAPublicKey publicKey

分析RSAPrivateKey:

RSAPrivateKey privateKey,通过函数privateKey.getAlgorithm()查看,或者通过privateKey.getEncoded()数据分析,可以得到默认是PKCS#8格式,
privateKey.getEncoded()的数据例子:

在这里插入图片描述
通过TLV分析工具查看:
在这里插入图片描述
在这里插入图片描述
可以看到,RSAPrivateKey privateKey里面,RSA密钥的参数N、E、D、P、Q等都包含在内的。
其中N、E是私钥对应的公钥RSAPublicKey publicKey,所需的全部参数。
因此,是可以从RSAPrivateKey privateKey拿到对应的RSAPublicKey publicKey

开发环境:

`IDE:eclipse版本4.20.0
编译器:JDK1.8
导入的包:bouncycastle,jar文件名bcprov-jdk18on-171.jar

转换函数:

public static byte[] p8PrvKey2P1PrvKeyBytes(PrivateKey privateKey) throws Exception {PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(privateKey.getEncoded());ASN1Encodable privateKeyPKCS1ASN1Encodable = privateKeyInfo.parsePrivateKey();ASN1Primitive asn1Primitive = privateKeyPKCS1ASN1Encodable.toASN1Primitive();        return asn1Primitive.getEncoded();} public static RSAPublicKey rsaGetPubKeyFromPriKey(RSAPrivateKey privateKey) {RSAPublicKeySpec rsaPubKeySpec = null;KeyFactory keyFactory = null;org.bouncycastle.asn1.pkcs.RSAPrivateKey rP = null;try {keyFactory = KeyFactory.getInstance("RSA");rP = org.bouncycastle.asn1.pkcs.RSAPrivateKey.getInstance(p8PrvKey2P1PrvKeyBytes(privateKey));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}try {keyFactory = KeyFactory.getInstance("RSA");rsaPubKeySpec = new RSAPublicKeySpec(rP.getModulus(), rP.getPublicExponent());return (RSAPublicKey) keyFactory.generatePublic(rsaPubKeySpec);} catch (InvalidKeySpecException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}
}

注意导入bcprov-jdk18on-171.jar中类

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;

还要注意,bouncycastle里面有RSAPrivateKey
jdk自带公共:java.security.interfaces.RSAPrivateKey;

bouncycastle包里面的:org.bouncycastle.asn1.pkcs.RSAPrivateKey

测试代码:

public static void main(String[] args) {		testRsa();
}public static void testRsa() {KeyPairGenerator keyPairGen;try {keyPairGen = KeyPairGenerator.getInstance("RSA");keyPairGen.initialize(2048, new SecureRandom());KeyPair keyPair = keyPairGen.generateKeyPair();RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();//System.out.println("privateKey:" + hexToString(privateKey.getEncoded(), 0, privateKey.getEncoded().length));//RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();RSAPublicKey publicKey = rsaGetPubKeyFromPriKey(privateKey);String out1 = encrypt("1234567890", publicKey);System.out.println("encrypt:" + out1);String out2 = decrypt(out1, privateKey);System.out.println("decrypt:" + out2);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}        
}public static String encrypt(String str, RSAPublicKey publicKey) throws Exception {//base64编码的公钥//byte[] decoded = Base64.getDecoder().decode(publicKey);//RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));//RSA加密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);String outStr = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));return outStr;
}
public static String decrypt(String str, RSAPrivateKey privateKey) throws Exception {//64位解码加密后的字符串byte[] inputByte = Base64.getDecoder().decode(str);//base64编码的私钥//byte[] decoded = Base64.getDecoder().decode(privateKey);//RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));//RSA解密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);String outStr = new String(cipher.doFinal(inputByte));return outStr;
}

测试结果:

在这里插入图片描述

http://www.lryc.cn/news/64999.html

相关文章:

  • Android 12.0 Launcher3仿ios长按app图标实现抖动动画开始拖拽停止动画
  • 【五一创作】50道Java面试题
  • 4。计算机组成原理(3)指令系统
  • 【Elasticsearch】NLP简单应用
  • 3. 云计算的落地实践(下)
  • javaEE+mysql学生竞赛管理系统
  • 车辆出险记录查询API接口
  • MySQL的概念,编译及安装
  • 系统性能压力测试
  • 从零开始学习Linux运维,成为IT领域翘楚(三)
  • 轻松搭建自己的ChatGPT聊天机器人,让AI陪你聊天!
  • CompletableFutrue异步处理
  • 【前端面经】JS-对象的可枚举性
  • 沁恒 CH32V208(三): CH32V208 Ubuntu22.04 Makefile VSCode环境配置
  • 日撸 Java 三百行day38
  • 玩转肺癌目标检测数据集Lung-PET-CT-Dx ——④转换成PASCAL VOC格式数据集
  • 两种使用 JavaScript 实现网页高亮关键字的方法
  • 【SpringBoot】SpringBoot集成ElasticSearch
  • 从 Elasticsearch 到 Apache Doris,10 倍性价比的新一代日志存储分析平台
  • 探讨Redis缓存问题及解决方案:缓存穿透、缓存击穿、缓存雪崩与缓存预热(如何解决Redis缓存中的常见问题并提高应用性能)
  • 【Python】怎么在pip下载的时候设置镜像?(常见的清华镜像、阿里云镜像以及中科大镜像)
  • 【AI面试】目标检测中one-stage、two-stage算法的内容和优缺点对比汇总
  • stack、queue和priority_queue的使用介绍--C++
  • python遍历数组
  • 红黑树理论详解与Java实现
  • container的讲解
  • JavaScript 箭头函数
  • 简单理解Transformer注意力机制
  • Vue3面试题:20道含答案和代码示例的练习题
  • Oracle数据库创建用户