0

Lets say, Person1 has two files: person1.public.key and person1.private.key. This person uses his person1.private.key to encrypt a message and send it to me.

I only have the file person1.public.key, and I want to decrypt the message sent to me.

How to:

  • encrypt the message on Person1's side?
  • decrypt the message on my side?

I did search online, but all examples I saw was the code generating the keys on runtime. I want to use the keys in the files.

jps
  • 20,041
  • 15
  • 75
  • 79
Wolfgang Amadeus
  • 398
  • 3
  • 12
  • 1
    If they are the receiver, you encrypt using their public key and they decrypt with their private key. If you are the receiver, you need your own private key and they use your public key. https://en.wikipedia.org/wiki/Public-key_cryptography – nullforce Sep 11 '22 at 01:43
  • Not necessarily. Using your private key to encrypt a message so the others can decrypt it with your public key is also a valid method. This is how Bitcoin works, for example. – Wolfgang Amadeus Sep 11 '22 at 01:53
  • 1
    This article says otherwise? https://bitzuma.com/posts/six-things-bitcoin-users-should-know-about-private-keys/ – nullforce Sep 11 '22 at 02:20
  • "Transactions are Messages Signed with a Private Key. [...] Anyone with a signature and public key can easily authenticate a message." – Wolfgang Amadeus Sep 11 '22 at 02:29
  • 3
    Right, but that's signing not encryption? I'd update your question to ask about signing. – nullforce Sep 11 '22 at 02:41
  • Oh, I see. There is a lot I still need to learn about RSA. Thank you for the clarification. – Wolfgang Amadeus Sep 11 '22 at 03:29

1 Answers1

1

Did you try using RSA.ImportFromPem(...)?

It supports the following PEM labels:

  • PUBLIC KEY
  • PRIVATE KEY
  • RSA PRIVATE KEY
  • RSA PUBLIC KEY
var keyString = loadFileIntoReadyOnlySpan();
var rsaKey = RSA.Create();
rsaKey.ImportFromPem(keyString);

I assume you know/can figure out how to load a file

jitter
  • 53,475
  • 11
  • 111
  • 124
  • This looks to be a solution, but I forgot to say that I'm using .Net Framework 4.8. There is any similar method available on 4.8? – Wolfgang Amadeus Sep 11 '22 at 01:21
  • 1
    @WolfgangAmadeus - For DER or PEM encoded keys on .NET Framework 4.8 it is most convenient to use BouncyCastle, s. e.g. [here](https://stackoverflow.com/a/63204020/9014097) – Topaco Sep 11 '22 at 06:01