[英]How to encrypt a string with private key and decrypt with public key?
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#.
如何在c#中实现这一点。 please help me with small code snippet.
请帮我一个小代码片段。 thanks
谢谢
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. AFAIK,虽然公钥和私钥之间的数学技术没有区别,但出于安全考虑,您需要始终如一地使用它们。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.