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

发布于 2024-12-07 13:24:39 字数 576 浏览 1 评论 0原文

当我使用 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(公共)和 PKCS#8(私有)。

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

谢谢

When I generate an RSA key pair using the Java API, the public key is encoded in the X.509 format and the private key is encoded in the PKCS#8 format. I'm looking to encode both as PKCS#1. Is this possible? I've spent a considerable amount of time going through the Java docs but haven't found a solution. The result is the same when I use the Java and the Bouncy Castle providers.

Here is a snippet of the code:

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();

The two resulting byte arrays are formatted as X.509 (public) and PKCS#8 (private).

Any help would be much appreciated. There are some similar posts but none really answer my question.

Thank You

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浅忆 2024-12-14 13:24:39

您将需要 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

谢谢

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

这些帖子包含有用但不完整且有时过时的信息(即对于较旧的信息) BouncyCastle 的版本),这帮助我构建了这篇文章。

You will need 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;

The code snippets below have been checked and found working with Bouncy Castle 1.52.

Private key

Convert private key from PKCS8 to 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();

Convert private key in PKCS1 to 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();

Check with command line OpenSSL that the key format is as expected:

openssl rsa -in rsa_private_key.pem -noout -text

Public key

Convert public key from X.509 SubjectPublicKeyInfo to PKCS1:

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

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

Convert public key in PKCS1 to 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();

Check with command line OpenSSL that the key format is as expected:

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

Thanks

Many thanks to the authors of the following posts:

Those posts contained useful, but incomplete and sometimes outdated info (i.e. for older versions of BouncyCastle), that helped me to construct this post.

灵芸 2024-12-14 13:24:39

RFC5208 开始,PKCS#8 未加密格式由 PrivateKeyInfo 结构:

PrivateKeyInfo ::= SEQUENCE {
  version                   Version,
  privateKeyAlgorithm       PrivateKeyAlgorithmIdentifier,
  privateKey                PrivateKey,
  attributes           [0]  IMPLICIT Attributes OPTIONAL }

其中 privateKey 是:

"...一个八位字节字符串,其内容是私钥的值。内容的解释在私钥算法的注册中定义。例如,对于 RSA 私钥,内容是RSAPrivateKey 类型值的 BER 编码。”

这个 RSAPrivateKey 结构只是密钥的 PKCS#1 编码,我们可以使用 BouncyCastle 提取它:

// pkcs8Bytes contains PKCS#8 DER-encoded key as a byte[]
PrivateKeyInfo pki = PrivateKeyInfo.getInstance(pkcs8Bytes);
RSAPrivateKeyStructure pkcs1Key = RSAPrivateKeyStructure.getInstance(
        pki.getPrivateKey());
byte[] pkcs1Bytes = pkcs1Key.getEncoded(); // etc.

From RFC5208, the PKCS#8 unencrypted format consists of a PrivateKeyInfo structure:

PrivateKeyInfo ::= SEQUENCE {
  version                   Version,
  privateKeyAlgorithm       PrivateKeyAlgorithmIdentifier,
  privateKey                PrivateKey,
  attributes           [0]  IMPLICIT Attributes OPTIONAL }

where privateKey is:

"...an octet string whose contents are the value of the private key. The interpretation of the contents is defined in the registration of the private-key algorithm. For an RSA private key, for example, the contents are a BER encoding of a value of type RSAPrivateKey."

This RSAPrivateKey structure is just the PKCS#1 encoding of the key, which we can extract using BouncyCastle:

// pkcs8Bytes contains PKCS#8 DER-encoded key as a byte[]
PrivateKeyInfo pki = PrivateKeyInfo.getInstance(pkcs8Bytes);
RSAPrivateKeyStructure pkcs1Key = RSAPrivateKeyStructure.getInstance(
        pki.getPrivateKey());
byte[] pkcs1Bytes = pkcs1Key.getEncoded(); // etc.
奢欲 2024-12-14 13:24:39

我写了一个C程序将pkcs8私钥转换为pkcs1。有用!

/*****************************************
    convert pkcs8 private key file to pkcs1

    2013-1-25   Larry Wu     created
 ****************************************/

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>

#include <openssl/rsa.h>
#include <openssl/bio.h> 
#include <openssl/err.h> 
#include <openssl/pem.h>
#include <openssl/engine.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <stdarg.h>

#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <set>
#include <list>
#include <vector>

using namespace std;


#define MY_TRACE_ERROR printf


/*
    gcc -Wall -o pkcs_8to1 pkcs_8to1.cpp -g -lstdc++ -lcrypto -lssl
*/
int main(int argc, char **argv)
{
    EVP_PKEY * pkey = NULL;
    string kin_fname;
    FILE *kin_file = NULL;
    string kout_fname;
    FILE *kout_file = NULL;

    // param
    if(argc != 3)
    {
        printf("Usage: %s <pkcs8_key_file> <pkcs1_key_file>\n", argv[0]);
        return 1;
    }

    kin_fname = argv[1];
    kout_fname = argv[2];


    // init
    OpenSSL_add_all_digests();
    ERR_load_crypto_strings();

    // read key
    if((kin_file = fopen(kin_fname.c_str(), "r")) == NULL)
    {
        MY_TRACE_ERROR("kin_fname open fail:%s\n", kin_fname.c_str());
        return 1;
    }

    if ((pkey = PEM_read_PrivateKey(kin_file, NULL, NULL, NULL)) == NULL) 
    {
        ERR_print_errors_fp(stderr);
        MY_TRACE_ERROR("PEM_read_PrivateKey fail\n");
        fclose(kin_file);
        return 2;
    }

    // write key
    if((kout_file = fopen(kout_fname.c_str(), "w")) == NULL)
    {
        MY_TRACE_ERROR("kout_fname open fail:%s\n", kout_fname.c_str());
        return 1;
    }

    if (!PEM_write_PrivateKey(kout_file, pkey, NULL, NULL, 0, NULL, NULL)) 
    {
        ERR_print_errors_fp(stderr);
        MY_TRACE_ERROR("PEM_read_PrivateKey fail\n");
        fclose(kout_file);
        return 2;
    }

    // clean
    fclose(kin_file);
    fclose(kout_file);
    EVP_PKEY_free(pkey);

    return 0;
}

I wrote a C programme to convert pkcs8 private key to pkcs1. It works!

/*****************************************
    convert pkcs8 private key file to pkcs1

    2013-1-25   Larry Wu     created
 ****************************************/

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>

#include <openssl/rsa.h>
#include <openssl/bio.h> 
#include <openssl/err.h> 
#include <openssl/pem.h>
#include <openssl/engine.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <stdarg.h>

#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <set>
#include <list>
#include <vector>

using namespace std;


#define MY_TRACE_ERROR printf


/*
    gcc -Wall -o pkcs_8to1 pkcs_8to1.cpp -g -lstdc++ -lcrypto -lssl
*/
int main(int argc, char **argv)
{
    EVP_PKEY * pkey = NULL;
    string kin_fname;
    FILE *kin_file = NULL;
    string kout_fname;
    FILE *kout_file = NULL;

    // param
    if(argc != 3)
    {
        printf("Usage: %s <pkcs8_key_file> <pkcs1_key_file>\n", argv[0]);
        return 1;
    }

    kin_fname = argv[1];
    kout_fname = argv[2];


    // init
    OpenSSL_add_all_digests();
    ERR_load_crypto_strings();

    // read key
    if((kin_file = fopen(kin_fname.c_str(), "r")) == NULL)
    {
        MY_TRACE_ERROR("kin_fname open fail:%s\n", kin_fname.c_str());
        return 1;
    }

    if ((pkey = PEM_read_PrivateKey(kin_file, NULL, NULL, NULL)) == NULL) 
    {
        ERR_print_errors_fp(stderr);
        MY_TRACE_ERROR("PEM_read_PrivateKey fail\n");
        fclose(kin_file);
        return 2;
    }

    // write key
    if((kout_file = fopen(kout_fname.c_str(), "w")) == NULL)
    {
        MY_TRACE_ERROR("kout_fname open fail:%s\n", kout_fname.c_str());
        return 1;
    }

    if (!PEM_write_PrivateKey(kout_file, pkey, NULL, NULL, 0, NULL, NULL)) 
    {
        ERR_print_errors_fp(stderr);
        MY_TRACE_ERROR("PEM_read_PrivateKey fail\n");
        fclose(kout_file);
        return 2;
    }

    // clean
    fclose(kin_file);
    fclose(kout_file);
    EVP_PKEY_free(pkey);

    return 0;
}
红尘作伴 2024-12-14 13:24:39

BouncyCastle 框架有一个 PKCS1 编码器来解决这个问题:http://www.bouncycastle。 org/docs/docs1.6/index.html

The BouncyCastle framework has a PKCS1 Encoder to solve this: http://www.bouncycastle.org/docs/docs1.6/index.html

情感失落者 2024-12-14 13:24:39

我试图使用移植到 BlackBerry 的 BountyCastle J2ME 库生成 DER 格式的 OpenSSL 友好的 RSA 公钥,我的代码:

public void testMe() throws Exception {
  RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
  generator.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001),
                 new SecureRandom(), 512, 80));
  AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();

  RSAKeyParameters params =  (RSAKeyParameters) keyPair.getPublic();
  RSAPublicKeyStructure struct = new RSAPublicKeyStructure(params.getModulus(), 
                                                           params.getExponent());

  SubjectPublicKeyInfo info = 
    new SubjectPublicKeyInfo(new AlgorithmIdentifier("1.2.840.113549.1.1.1"), 
                             struct);

  byte[] bytes = info.getDEREncoded();

  FileOutputStream out = new FileOutputStream("/tmp/test.der");

  out.write(bytes);
  out.flush();
  out.close();
}

密钥仍然不正确:

$ openssl asn1parse -in test.der -inform DER -i
0:d=0  hl=2 l=  90 cons: SEQUENCE          
2:d=1  hl=2 l=  11 cons:  SEQUENCE          
4:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
15:d=1  hl=2 l=  75 prim:  BIT STRING     

我更改了 org.bouncycastle.asn1.x509.AlgorithmIdentifier

public AlgorithmIdentifier(
    String     objectId)
{
    this.objectId = new DERObjectIdentifier(objectId);
    // This line has been added
    this.parametersDefined = true;
}

现在有了很好的密钥:

$ openssl asn1parse -in test.der -inform DER -i
0:d=0  hl=2 l=  92 cons: SEQUENCE          
2:d=1  hl=2 l=  13 cons:  SEQUENCE          
4:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
15:d=2  hl=2 l=   0 prim:   NULL              
17:d=1  hl=2 l=  75 prim:  BIT STRING 

这可以是用于加密:

$ echo "123" | openssl rsautl -pubin  -inkey test.der -encrypt -keyform DER -out y
$ wc -c y
64 y

I was trying to generate OpenSSL-friendly RSA public keys in DER format using BountyCastle J2ME library ported to BlackBerry, my code:

public void testMe() throws Exception {
  RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
  generator.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001),
                 new SecureRandom(), 512, 80));
  AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();

  RSAKeyParameters params =  (RSAKeyParameters) keyPair.getPublic();
  RSAPublicKeyStructure struct = new RSAPublicKeyStructure(params.getModulus(), 
                                                           params.getExponent());

  SubjectPublicKeyInfo info = 
    new SubjectPublicKeyInfo(new AlgorithmIdentifier("1.2.840.113549.1.1.1"), 
                             struct);

  byte[] bytes = info.getDEREncoded();

  FileOutputStream out = new FileOutputStream("/tmp/test.der");

  out.write(bytes);
  out.flush();
  out.close();
}

Key was still incorrect:

$ openssl asn1parse -in test.der -inform DER -i
0:d=0  hl=2 l=  90 cons: SEQUENCE          
2:d=1  hl=2 l=  11 cons:  SEQUENCE          
4:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
15:d=1  hl=2 l=  75 prim:  BIT STRING     

I changed org.bouncycastle.asn1.x509.AlgorithmIdentifier

public AlgorithmIdentifier(
    String     objectId)
{
    this.objectId = new DERObjectIdentifier(objectId);
    // This line has been added
    this.parametersDefined = true;
}

And now have nice key:

$ openssl asn1parse -in test.der -inform DER -i
0:d=0  hl=2 l=  92 cons: SEQUENCE          
2:d=1  hl=2 l=  13 cons:  SEQUENCE          
4:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
15:d=2  hl=2 l=   0 prim:   NULL              
17:d=1  hl=2 l=  75 prim:  BIT STRING 

Which can be used to encrypt:

$ echo "123" | openssl rsautl -pubin  -inkey test.der -encrypt -keyform DER -out y
$ wc -c y
64 y
爱的那么颓废 2024-12-14 13:24:39

我知道这是旧帖子。但我花了两天时间解决这个问题,终于发现 BouncyCastle 可以做到这一点

ASN1可编码

http://www.bouncycastle.org/docs/ docs1.5on/org/bouncycastle/asn1/ASN1Encodable.html

I know this is old post. but I spent two days to solve this problem and finally find BouncyCastle can do that

ASN1Encodable

http://www.bouncycastle.org/docs/docs1.5on/org/bouncycastle/asn1/ASN1Encodable.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文