Java从KeyPair对象检索公钥的实际值[英] Java Retrieve the actual value of the public key from the KeyPair object

问题描述

我想问一下如何从键盘对象检索私钥和公共密钥的实际值,因为我需要导出它们并保存在数据库中.

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格式编码.

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: \n" + prv_recovered.toString());
System.out.println("Public Key: \n" + pub_recovered.toString());

其他推荐答案

您可以简单地降到RSAPrivateKey和RSAPublicKey.完成后,您可以访问这些类的方法.

RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic());
BigInteger modulus = pubKey.getModulus();

等.

其他推荐答案

您是否查看了文档?

尝试以下内容:

getmodulus

他们都返回 biginteger"> biginteger

依次存储.

还查看原始编码格式有帮助.

本文地址:https://www.itbaoku.cn/post/978346.html