Click here to Skip to main content
16,015,531 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the public key shared with me in a text file. (BEGIN CERTIFICATE-END CERTIFICATE).
How do I encrypt a message in C# using this public key text?

Similarly I have my private key in text format.(BEGIN PRIVATE KEY-END PRIVATE KEY).
Ho do I decrypt a message in C# using this private key as text?


What am I missing?

Kindly guide me.

What I have tried:

I have searched through examples on the net, but did not find any that uses public/private keys in text format?

Do I need to convert these text files into some other format?
Posted
Updated 27-May-21 23:05pm
Comments
Richard MacCutchan 27-May-21 3:37am    
In encryption/decryption, data is just considered as a stream of bytes. The encryption code does not try to understand its format.
DerekT-P 27-May-21 15:36pm    
I think the OP means that he has the keys in text file format; not the encrypted message.

But if you have the other party's public key, you need THEIR private key to decrypt it. Which, by definition, you don't have - it's private (to them). If they are sending you an encrypted message, they have encrypted it using YOUR public key (which, being public, you can share with them in advance). Then you use your private key to decrypt it. Sounds like you have THEIR public key and YOUR private key - so you don't have both parts of any public/private key combo, so can't decrypt.
Member 3654288 28-May-21 1:25am    
I am really sorry for the confusion You are absolutely correct. I have their public key. I will send my message using that for encryption. It is in text format. How do I do that using C#. Can you or someone else point me in the right direction?


1 solution

There are various suggestions for reading the key from a file in this StackOverflow thread:
c# - How to read a PEM RSA private key from .NET - Stack Overflow[^]

Essentially, it's easy to do in .NET 5, but a bit of a pain in .NET Framework unless you use a third-party library.

If you can install the key as a certificate in the certificate store on the PC where your code will run, then it's slightly easier to use:
PublicKey Class (System.Security.Cryptography.X509Certificates) | Microsoft Docs[^]
 
Share this answer
 
Comments
Member 3654288 29-May-21 0:41am    
Thanks, Rchards. I shall havve a look at those links.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900