简体   繁体   中英

C# - Load .DER public key from file and use for encryption

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!

You can use the X509Certificate2 to load the certificate, IE:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM