0

I have a public key in a .der extension file from a vendor. I have to use this to encrypt something using C# and add the result to an API call. I am new to this type of stuff and can't figure out how to load the key in the .der file into code and use it to encrypt my string. Any help?

Thanks!

Vamshi
  • 1
  • 2
  • See https://stackoverflow.com/questions/11506891/how-to-load-the-rsa-public-key-from-file-in-c-sharp; though if you have a DER encoded file you should skip to after they do the Base64Decode operation when reading the PEM format. – bartonjs Oct 19 '18 at 17:34

1 Answers1

-2

You can use the X509Certificate2 to load the certificate, I.E.:

var cert = new X509Certificate2(@"C:\path\to\key.der");

var publicKey = cert.GetRSAPublicKey();
var privateKey = cert.GetRSAPrivateKey();

To actually encrypt/decrypt data, you would do something similar to the following depending on the specifications

var plaintext = Encoding.UTF8.GetBytes("Some Secret");

var encrypted = publicKey.Encrypt(plaintext, RSAEncryptionPadding.OaepSHA256);

var decrypted = privateKey.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA256);

Console.WriteLine(Encoding.UTF8.GetString(decrypted));
Eric Damtoft
  • 1,353
  • 7
  • 13
  • I tried something similar. The very first line throws the following error: "Cannot find the requested object". The key file exists and the path I provided in the X509Certificate2 constructor is correct. I have a some java code (in jar files) provided by the vendor to test the key and it works when using the same key from the same location. I just need to do this using C#/.NET. – Vamshi Sep 26 '18 at 01:06
  • 2
    The X509Certificate2 constructor can only read certificates, PKCS7 signed data, and PKCS12/PFX. It can't read raw asymmetric keys. – bartonjs Oct 19 '18 at 17:31