1

I'm trying to encrypt a string using a PEM public key file in dotnet core (1.1) and my question is: How do I do this?

I thought this would simply be a case of:

var cert = new X509Certificate2("path_to_public_key.pem");
using (var rsa = cert.GetRSAPublicKey())
{
    // encrypt here
}

However, when I try to new up the certificate I get the following error:

error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error

The PEM file looks like this:

-----BEGIN PUBLIC KEY-----
... ANBgkqhkiG9w0BAQEFA ...
(loads more text)
-----END PUBLIC KEY-----

I've checked the pem file and there are no extraneous ^M characters anywhere (as from a suggest cause of the error here).

(I'm on macOS Sierra if that makes any difference)

Any help would be greatly appreciated!

stush
  • 67
  • 2
  • 10
  • 2
    You seem to have a public key and not a certificate. I guess you shouldn't use `X509Certificate2`. – Artjom B. Aug 12 '17 at 16:50
  • @ArtjomB. Thank you! You sent me down the right path. (It's so obvious when someone points it out!). – stush Aug 12 '17 at 17:39

1 Answers1

1

Artjom B's comment sent me down the right path. A public key is indeed not a certificate.

Solution came from this excellent post.

For dotnet core (which doesn't have a RSACryptoServiceProvider class) I made a couple of minor modifications. You can return an RSAParameters object from GetRSAProviderFromPemFile, you can then use that like:

using (var rsa = RSA.Create()
{
   rsa.ImportParameters(GetRSAProviderFromPemFile("path_to_pem.pem"));
   var encrypted = rsa.Encrypt( ... );
}
stush
  • 67
  • 2
  • 10
  • 2
    How did you initialize RSAParameters with given example of `GetRSAProviderFromPemFile`? – niklas-e Dec 04 '18 at 08:28
  • But `RSACryptoServiceProvider` is available in .NET Core since v1.0 https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsacryptoserviceprovider?view=netcore-3.1#moniker-applies-to – mshwf Sep 22 '20 at 10:23