i never work with encryption library but i want to encrypt a string with private key and decrypt by public key. how to achieve this in c#. please help me with small code snippet. thanks
-
1You shouldn't encrypt arbitrary strings with RSA. You should encrypt a randomly generated **correctly padded** symmetric key with RSA. – CodesInChaos Jan 28 '11 at 16:15
-
1@CodeInChaos: I agree that that is what RSA is being used for most of the time but using RSA is not restricted to that. – Emond Jan 28 '11 at 17:21
-
AFAIK RSA isn't secure for encoding arbitrary unpadded strings. – CodesInChaos Jan 28 '11 at 17:24
-
1I'm afraid you are missing the concept here. There is no use if you use the private key for encryption since anybody can decrypt it using your public key (that's public right? :) If what you really want is encrypting some text, look at symmetric encryption instead. If you want to use RSA at any cost, use public key of the recipient to encrypt your data, not your own private key. – Ε Г И І И О Feb 28 '12 at 11:24
-
Or maybe he wanted to do that, but needed an essential building block for doing so. It is possible to encrypt both ways, their public followed by your private key, in order to guarantee both origin and destination. – Zoey May 18 '13 at 23:10
-
I agree all the comments about the purpose of private key. But note that the OP is asking how to encrypt a string with private key.. I meet the exact same requirement today! – Yang You Sep 25 '20 at 02:42
1 Answers
AFAIK, Although there's technically no difference in the math between a public and private key, you need to use them consistently for security reasons.
You're asking to encrypt with the private key and decrypt with the public key. This is generally the wrong way around. If you want to go this direction, it's usually an operation called "digitally signing".
If you sign with the private key such that it is reversible by the public key, then it's not really a secret. I assume you're just trying to authenticate the message as being legitimately from the sender. What you need is digital signatures - still performed with the public-key-private-key (or "asymmetric") key.
With digital signatures, the message itself is not secret (there's no need since anyone with the public key could decrypt it anyway) but is accompanied by additional data, based on the message, that is verifiable using the public key and could have only been computed by someone with matching private key.
It would look something like the following. Now you just have to figure out where you'll get the key.
static byte[] GenerateDigitalSignature(byte[] data, RSAParameters asymmetricKey)
{
using (var rcsp = new RSACryptoServiceProvider())
using (var cp = new SHA1CryptoServiceProvider())
{
rcsp.ImportParameters(asymmetricKey);
return rcsp.SignData(data, cp);
}
}

- 20,024
- 18
- 75
- 125