-->

Creating PKCS1 public key in Net Framework

2019-07-21 09:02发布

问题:

I need to create an RSA 1024 bit "PKCS1 public key without PEM headers" and store it as an array of bytes. In Net. Framework I have 2 arrays: RSAParameters.Modulus and RSAParameters.Exponent (which constitue a public key as I understand). How can I convert these two arrays into a "PKCS1 public key without PEM headers"?

Thank you.

回答1:

If you need to encode only RSA public key, you can write your own wrapper, it will take 5 lines of coding. RSA public key should be represented as the following ASN.1 structure:

RSAPublicKey ::= SEQUENCE { modulus INTEGER, -- n publicExponent INTEGER -- e }

However, this will need you to learn some ASN.1 basics. Also, you should make sure that you need to save only in this format, applications could also require algorithmIdentifier to be added.



回答2:

There must be an easier way, but one way is to use the Bouncycastle C# library and a few of its classes as in the following example:

using System.Security.Cryptography;
using Org.BouncyCastle.Asn1;

    public static byte[] DEREncode(RSACryptoServiceProvider rsa)
    {
        RSAParameters rsaParams = rsa.ExportParameters(false);
        DerInteger n = new DerInteger(rsaParams.Modulus);
        DerInteger e = new DerInteger(rsaParams.Exponent);
        DerSequence seq = new DerSequence(new Asn1Encodable[] {n, e});
        return seq.GetEncoded();
    }