转载

在Java中生成PKCS#1格式的RSA密钥

当使用Java API生成RSA密钥对时,公钥以X.509格式编码,私钥以PKCS#8格式编码.我正在寻找编码PKCS#1.这可能吗?我花了大量的时间来完成Java文档,但还没有找到解决方案.当我使用Java和Bouncy Castle提供商时,结果是一样的.

以下是代码段:

KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA","BC");
keygen.initialize(1024);
KeyPair pair = keygen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
byte[] privBytes = priv.getEncoded();
byte[] pubBytes = pub.getEncoded();

两个生成的字节数组格式为X.509(public)和PKCS#8(private).

任何帮助将不胜感激.有一些类似的帖子,但没有一个真的回答我的问题.

谢谢

你会需要BouncyCastle:

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;

下面的代码片段已被检查,并发现与Bouncy Castle 1.52一起工作.

私钥

将私钥从PKCS8转换为PKCS1:

PrivateKey priv = pair.getPrivate();
byte[] privBytes = priv.getEncoded();

PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(privBytes);
ASN1Encodable encodable = pkInfo.parsePrivateKey();
ASN1Primitive primitive = encodable.toASN1Primitive();
byte[] privateKeyPKCS1 = primitive.getEncoded();

将PKCS1中的私钥转换为PEM:

PemObject pemObject = new PemObject("RSA PRIVATE KEY", privateKeyPKCS1);
StringWriter stringWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(stringWriter);
pemWriter.writeObject(pemObject);
pemWriter.close();
String pemString = stringWriter.toString();

使用命令行OpenSSL检查密钥格式是否符合预期:

openssl rsa -in rsa_private_key.pem -noout -text

公钥

将公钥从X.509 SubjectPublicKeyInfo转换为PKCS1:

PublicKey pub = pair.getPublic();
byte[] pubBytes = pub.getEncoded();

SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(pubBytes);
ASN1Primitive primitive = spkInfo.parsePublicKey();
byte[] publicKeyPKCS1 = primitive.getEncoded();

将PKCS1中的公钥转换为PEM:

PemObject pemObject = new PemObject("RSA PUBLIC KEY", publicKeyPKCS1);
StringWriter stringWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(stringWriter);
pemWriter.writeObject(pemObject);
pemWriter.close();
String pemString = stringWriter.toString();

使用命令行OpenSSL检查密钥格式是否符合预期:

openssl rsa -in rsa_public_key.pem -RSAPublicKey_in -noout -text

谢谢

非常感谢以下帖子的作者:

> http://stackoverflow.com/a/8713518/1016580

> http://stackoverflow.com/a/14052651/1016580

> http://stackoverflow.com/a/14068057/1016580

那些帖子包含有用的,虽然有时是过时的信息(即对于旧版本的BouncyCastle),这有助于我构建这个帖子.

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/7611383/generating-rsa-keys-in-pkcs1-format-in-java

原文  https://codeday.me/bug/20181016/293302.html
正文到此结束
Loading...