GVKun编程网logo

RSA无视PEM文件格式(pkcs#1,pkcs#8,有无密码 )直接读取PEM文件为PrivateKey,PublicKey

5

在这篇文章中,我们将为您详细介绍RSA无视PEM文件格式的内容,并且讨论关于pkcs#1,pkcs#8,有无密码直接读取PEM文件为PrivateKey,PublicKey的相关问题。此外,我们还会涉

在这篇文章中,我们将为您详细介绍RSA无视PEM文件格式的内容,并且讨论关于pkcs#1,pkcs#8,有无密码 直接读取PEM文件为PrivateKey,PublicKey的相关问题。此外,我们还会涉及一些关于c – openSSL:PEM_write_RSAPublicKey和PEM_write_RSA_PUBKEY之间的区别、EC将字符串转换为PublicKey / PrivateKey、Generating RSA keys in PKCS#1 format in Java--转、golang x509.MarshalPKIXPublicKey vs x509.MarshalPKCS1PublicKey()的知识,以帮助您更全面地了解这个主题。

本文目录一览:

RSA无视PEM文件格式(pkcs#1,pkcs#8,有无密码 )直接读取PEM文件为PrivateKey,PublicKey

RSA无视PEM文件格式(pkcs#1,pkcs#8,有无密码 )直接读取PEM文件为PrivateKey,PublicKey

 RSA无视PEM文件格式(pkcs#1,pkcs#8,有无密码 )直接读取PEM文件为PrivateKey,PublicKey

凶残暴力


import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
import org.bouncycastle.pkcs.PKCSException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringReader;
import java.security.Key;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * RSA无视PEM文件格式(pkcs#1,pkcs#8,有无密码 )直接读取PEM文件为PrivateKey,PublicKey
 */
public class RSAUtil {
    private final static Logger logger = LoggerFactory.getLogger(RSAUtil.class);

    static {
        java.security.Security.addProvider(
                new org.bouncycastle.jce.provider.BouncyCastleProvider()
        );

    }

    public static PrivateKey privateKey(String pemString, String password) {
        try {
            return (PrivateKey) parseKey(pemString, password);
        } catch (IOException e) {
            logger.error("privateKey error", e);
            e.printStackTrace();
        }
        return null;
    }

    public static PrivateKey privateKey(String pemString) {
        try {
            return (PrivateKey) parseKey(pemString, null);
        } catch (IOException e) {
            logger.error("privateKey error", e);
        }
        return null;
    }

    public static PublicKey publicKey(String pemString) {
        try {
            return (PublicKey) parseKey(pemString, null);
        } catch (IOException e) {
            logger.error("publicKey error", e);
        }
        return null;
    }

    /**
     * Parses a Key instance from a PEM representation.
     * <p>
     * When the provided key is encrypted, the provided pass phrase is applied.
     *
     * @param pemString  a PEM representation of a private key (cannot be null or empty)
     * @param passPhrase optional pass phrase (must be present if the private key is encrypted).
     * @return a  Key instance (never null)
     */
    public static Key parseKey(String pemString, String passPhrase) throws IOException {

        if (passPhrase == null) {
            passPhrase = "";
        }
        try (StringReader reader = new StringReader(pemString); //
             PEMParser pemParser = new PEMParser(reader)) {

            final Object object = pemParser.readObject();
            final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);

            final KeyPair kp;

            if (object instanceof PEMEncryptedKeyPair) {
                // Encrypted key - we will use provided password
                final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passPhrase.toCharArray());
                kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
            } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                // Encrypted key - we will use provided password
                try {
                    final PKCS8EncryptedPrivateKeyInfo encryptedInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    final InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passPhrase.toCharArray());
                    final PrivateKeyInfo privateKeyInfo = encryptedInfo.decryptPrivateKeyInfo(provider);
                    return converter.getPrivateKey(privateKeyInfo);
                } catch (PKCSException | OperatorCreationException e) {
                    throw new IOException("Unable to decrypt private key.", e);
                }
            } else if (object instanceof PrivateKeyInfo) {
                return converter.getPrivateKey((PrivateKeyInfo) object);
            } else if (object instanceof SubjectPublicKeyInfo) {
                return converter.getPublicKey((SubjectPublicKeyInfo) object);
            } else {
                // Unencrypted key - no password needed
                kp = converter.getKeyPair((PEMKeyPair) object);
            }
            return kp.getPrivate();
        }
    }


}

 

c – openSSL:PEM_write_RSAPublicKey和PEM_write_RSA_PUBKEY之间的区别

c – openSSL:PEM_write_RSAPublicKey和PEM_write_RSA_PUBKEY之间的区别

在openssl库中,我可以看到两种将公钥写入文件的方法:

int PEM_write_RSAPublicKey(FILE *fp,RSA *x);
int PEM_write_RSA_PUBKEY(FILE *fp,RSA *x);

在文档中,我可以看到:

The RSAPublicKey functions process an RSA public key using an RSA
structure. The public key is encoded using a PKCS#1 RSAPublicKey
structure.

The RSA_PUBKEY functions also process an RSA public key using an RSA
structure. However the public key is encoded using a
SubjectPublicKeyInfo structure and an error occurs if the public key
is not RSA

但我不明白是什么

SubjectPublicKeyInfo

两种方法之间的基本面差异是什么!

解决方法

SubjectPublicKeyInfo – 公钥的ASN1结构,在rfc 3280(Internet X.509公钥基础结构)中描述.事实上,这种格式包含公钥算法的id和公钥本身.在这种情况下,此公钥是根据pkcs1标准格式化的.所以X.509格式是更高级的格式,它不仅描述了RSA公钥,而且描述了公钥.

EC将字符串转换为PublicKey / PrivateKey

EC将字符串转换为PublicKey / PrivateKey

如何解决EC将字符串转换为PublicKey / PrivateKey?

我一直在尝试将下面粘贴的代码转换为公钥。我正在尝试创建一个共享机密。我有密钥的未压缩十六进制表示形式。我想从中创建一个公钥。同样,我也希望创建私钥并在之后加入它们。

String plainPublicKey = "042E3E5CCF6B9AB04BE7A22F3FACCFDE73C87E87155394A34815408A896CA18A374DAC669AF3BF6220FC863767F4AF47507C5BC221FC4A19874DAF39B4074E3EB8";
        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Hex.decodeHex(plainPublicKey.tochararray()));
        KeyFactory kf = KeyFactory.getInstance("EC");
        PublicKey pub = kf.generatePublic(publicKeySpec);
        return pub;
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at jdk.crypto.ec/sun.security.ec.ECKeyFactory.engineGeneratePublic(ECKeyFactory.java:157)
    at java.base/java.security.KeyFactory.generatePublic(KeyFactory.java:352)
    at AESExample.getPublicKey(AESExample.java:66)
    at AESExample.main(AESExample.java:74)
Caused by: java.security.InvalidKeyException: invalid key format
    at java.base/sun.security.x509.X509Key.decode(X509Key.java:386)
    at java.base/sun.security.x509.X509Key.decode(X509Key.java:401)
    at jdk.crypto.ec/sun.security.ec.EcpublicKeyImpl.<init>(EcpublicKeyImpl.java:71)
    at jdk.crypto.ec/sun.security.ec.ECKeyFactory.implGeneratePublic(ECKeyFactory.java:219)
    at jdk.crypto.ec/sun.security.ec.ECKeyFactory.engineGeneratePublic(ECKeyFactory.java:153)
    ... 3 more

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Generating RSA keys in PKCS#1 format in Java--转

Generating RSA keys in PKCS#1 format in Java--转

原文地址:https://stackoverflow.com/questions/7611383/generating-rsa-keys-in-pkcs1-format-in-java

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:

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

You will need BouncyCastle:

encodable

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

Private key

Convert private key from PKCS8 to PKCS1:

<span>PrivateKeyInfo<span> pkInfo <span>=<span> <span>PrivateKeyInfo<span>.<span>getInstance<span>(<span>privBytes<span>);<span>
ASN1encodable encodable <span>=<span> pkInfo<span>.<span>parsePrivateKey<span>();<span>
ASN1Primitive primitive <span>=<span> encodable<span>.<span>toASN1Primitive<span>();<span>
<span>byte<span>[]<span> privateKeyPKCS1 <span>=<span> primitive<span>.<span>getEncoded<span>();

Convert private key in PKCS1 to PEM:

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

Public key

Convert public key from X.509 SubjectPublicKeyInfo to PKCS1:

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

Convert public key in PKCS1 to PEM:

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

Thanks

Many thanks to the authors of the following posts:

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

golang x509.MarshalPKIXPublicKey vs x509.MarshalPKCS1PublicKey()

golang x509.MarshalPKIXPublicKey vs x509.MarshalPKCS1PublicKey()

谁能帮助我理解MarshalPKIXPublicKey()和MarshalPKCS1PublicKey()之间的区别?

根据评论:
// MarshalPKIXPublicKey将公钥序列化为DER编码的PKIX格式.

// MarshalPKCS1PublicKey将RSA公钥转换为PKCS#1,ASN.1 DER表单.

什么是DER编码的PKIX格式?

谢谢

解决方法

你没有说明你没有(或确实)理解了多少.从基础开始:

ASN.1(抽象语法表示法一)是用于定义要在系统或程序之间传递或互换的数据结构的一般方案.

DER(可分辨编码规则)是定义为将ASN.1数据编码为可以传送和/或存储的字节序列的方案,并且将这些字节序列无损地解码回ASN.1数据.

PKCS1 aka RFC 2313,2437,3447,8017(公钥加密标准#1)是定义使用RSA算法的一系列事项的标准,其中Appendix A定义了名为RSAPublicKey的ASN.1结构来表示RSA公钥.,与任何ASN.1结构一样,可以进行DER编码.

MarshalPKCS1PublicKey converts an RSA public key to PKCS#1,ASN.1 DER form.

清楚地表示PKCS1中RSA公钥的ASN.1结构的DER编码.

PKIX(公钥基础设施X.509)是X.509标准的互联网变体(正式地,简介),最初由当时的CCITT-ITU-T定义,目前在rfc5280.X.509和PKIX,主要定义公钥证书的格式,它将公钥与身份以及其他元数据绑定在一起.要做到这一点,它必须包含一个可以处理多个公钥算法的公钥的表示,使用SubjectPublicKeyInfo structure完成,相当简单,由an AlgorithmIdentifier that identifies the algorithm,plus a BIT STRING that contains the actual public-key value in an algorithm-dependent manner组成.RSA的算法相关部分在rfc3279 sec 2.3.1中指定,如你所见,它是来自PKCS1的RSAPublicKey结构,DER编码.

因此,RSA公钥的“DER编码的PKIX格式”表示PKIX / X.509 SubjectPublicKeyInfo结构的DER编码,其包含RSA的algorithmIdentifier(OID 1.2.840.113549.1.1.1和参数NULL)和包含该RSI的BIT STRING. DER编码PKCS1 RSAPublicKey.

相关或类似(尽管大多数包括私人非公开和/或PEM而不是DER):
How to store/retrieve RSA public/private key
How do we convert a String from PEM to DER format
Problem transmiting a RSA public key,javaME,bouncy castle
Generating RSA keys in PKCS#1 format in Java
How to generate PKCS#1 RSA keys in PEM Format?
Converting RSA keys into SubjectPublicKeyInfo Form from BigIntegers
Convert a X509 Public key to RSA public key
Load public key to create rsa object for public encryption
和交叉堆栈:
https://crypto.stackexchange.com/questions/19149/what-is-the-technical-name-for-a-public-key-container-in-der-format
https://crypto.stackexchange.com/questions/54121/rsa-key-differences-openssl-cli-vs-openssl-ssl-h-c-function

我们今天的关于RSA无视PEM文件格式pkcs#1,pkcs#8,有无密码 直接读取PEM文件为PrivateKey,PublicKey的分享已经告一段落,感谢您的关注,如果您想了解更多关于c – openSSL:PEM_write_RSAPublicKey和PEM_write_RSA_PUBKEY之间的区别、EC将字符串转换为PublicKey / PrivateKey、Generating RSA keys in PKCS#1 format in Java--转、golang x509.MarshalPKIXPublicKey vs x509.MarshalPKCS1PublicKey()的相关信息,请在本站查询。

本文标签: