Java Retrieve the actual value of the public key from the KeyPair object(Java 从 KeyPair 对象中检索公钥的实际值)
问题描述
我想问如何从 KeyPair 对象中检索私钥和公钥的实际值,因为我需要将它们导出并保存在数据库中.
I wanted to ask how to retrieve the actual values of the private and public keys from the KeyPair object because i need to export them and save in a database.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keyPair = kpg.genKeyPair();
System.out.println("Public key " + keyPair.getPublic());
System.out.println("Private key " + keyPair.getPrivate());
输出是:
Public key Sun RSA public key, 1024 bits
modulus: 105712092415375085805423498639048173422142354311030811647243014925610093650322108853068042919471115278002432342007597147610508132502035047888382465733153739247741208519707861808073276783311634229563965825609200080862631487160732889423591650215084096832366499080850540875321197564283324922935557797293830551071
public exponent: 65537
Private key sun.security.rsa.RSAPrivateCrtKeyImpl@35e71
推荐答案
使用 keypair.getPublic.getEncoded()
或 keypair.getPrivate.getEncoded()
:
RSA 私钥采用 PKCS#8 格式编码,公钥采用 X.509 格式编码.
RSA private keys are encoded in PKCS#8 format, and public keys are encoded in X.509 format.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pub = keyPair.getPublic();
PrivateKey prv = keyPair.getPrivate();
byte[] pubBytes = pub.getEncoded();
byte[] prvBytes = prv.getEncoded();
// now save pubBytes or prvBytes
// to recover the key
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey prv_recovered = kf.generatePrivate(new PKCS8EncodedKeySpec(prvBytes));
PublicKey pub_recovered = kf.generatePublic(new X509EncodedKeySpec(pubBytes));
System.out.println("Private Key:
" + prv_recovered.toString());
System.out.println("Public Key:
" + pub_recovered.toString());
这篇关于Java 从 KeyPair 对象中检索公钥的实际值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 从 KeyPair 对象中检索公钥的实际值
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01