How to encrypt a string with private key and decry

2020-07-07 05:19发布

问题:

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

回答1:

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


标签: c# encryption