0

I have RSA public key of size 2048 bits (as shown below):

-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjAc8U25mMDj93zGs6lEm 5HUbb22tLpWF8z13Lc4tRqNZ1WCGemI6fOhN1r1dkYpfMWakRqiCDX72gKi37zRX XJhYz9F8qUXCzGPdCWhr2Eywyl5YKsCV+wnHjRPL++aqBEMBTrKsxrPByGjDxpYW I/DgPinUWkZbSeIOZ4JX7Ze3SPNKDbDvJ5Ls2qGuFymtnpxWHbvWbHW1JuT4oHAd 1AhYOIRhVTRN+AGIgwvM0kpOsNH4P8KwhVe2CD6Pz6+54ealf1SctrE/X2EohigO aG4O2QtGGc/FxnzhdHpLpcXiYhA6EFll+D3DdU6Hb4iBMYiQQBlFnf/A6Evuix+L dQIDAQAB -----END PUBLIC KEY-----

Is there a way to get the key's modulus and exponent by using .net core (without writing any custom function)?

Raghu
  • 2,859
  • 4
  • 33
  • 65

1 Answers1

3

The public key has a X.509-PEM-format. For .NET Core 3.0 there is a built-in support with the ImportSubjectPublicKeyInfo-method of the RSA-class:

// publicKeyX509PEM: String containig the key-data
byte[] publicKeyX509DER = ConvertX509PemToDer(publicKeyX509PEM);
RSA rsa = RSA.Create();
rsa.ImportSubjectPublicKeyInfo(publicKeyX509DER, out _);
RSAParameters parameters = rsa.ExportParameters(false);

// get parameters.Exponent and parameters.Modulus

Note, that the ImportSubjectPublicKeyInfo-method processes only the DER-format which is essentially the binary format of the PEM-format (for more details see here). Thus, the PEM-format must first be converted into the DER-format, e.g. with

private static byte[] ConvertX509PemToDer(string pemContents)
{
    return Convert.FromBase64String(pemContents
        .TrimStart("-----BEGIN PUBLIC KEY-----".ToCharArray())
        .TrimEnd("-----END PUBLIC KEY-----".ToCharArray())
        .Replace("\r\n", ""));
}

Alternatively, OpenSSL can also be used for the conversion:

openssl rsa -pubin -inform PEM -outform DER -in <path to pem-input-file> -out <path to der-output-file>
Topaco
  • 40,594
  • 4
  • 35
  • 62
  • 2
    Maybe Microsoft can just copy your answer into its documentation ;) – President James K. Polk Jun 06 '19 at 13:33
  • Topaco: Once I get the file in DER format, can I use the built-in functions in .net core 2.2 to import? – Raghu Jun 06 '19 at 18:32
  • @Raghu This is a new method from Core 3.0 that does not exist in [Core 2.2](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsa?view=netcore-2.2). To my knowledge there is no built-in support in Core 2.2. This requires third-party libraries such as BouncyCastle, e.g. with the [`PublicKeyFactory.createKey`](https://stackoverflow.com/questions/17159147/inverse-operation-to-publickeyfactory-createkey/)-method, or custom code, e.g. something like the [`PemKeyUtils.DecodeX509PublicKey`](https://stackoverflow.com/a/49889680/9014097)-method. – Topaco Jun 07 '19 at 05:46