本文介绍了如何使用.pfx证书进行加密,解密和签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的计算机上有一个.pfx证书文件.我想用公钥加密邮件,然后用私钥解密.

I have a .pfx certificate file on my computer. I want to to encrypt a message with its public key, and then decrypt it with the private.

我还想用其私钥对另一条消息进行签名,然后检查签名.而且我需要从该消息中获取有关签名消息的证书的信息.

Also I want to sign another message with its private key, and then check the signature. And I need to get the information about the sertificate the message was signed with from that message.

如何使用System.Security.Cryptography做到这一点?

How can I do it using System.Security.Cryptography?

推荐答案

您可以在.NET中打开PFX,如下所示:

You can open the PFX in .NET, like the following:

var path = <YOUR PFX FILE PATH>;
var password = <YOUR PASSWORD>;

var collection = new X509Certificate2Collection();

collection.Import(path, password, X509KeyStorageFlags.PersistKeySet);

然后,枚举 X509Certificate2Collection .拥有证书后(假设只有一个证书),然后:

Then, enumerate over the X509Certificate2Collection. Once you have a certificate (assuming there is a single certificate), then:

var certificate = collection[0];

要加密数据,可以使用:

To encrypt data, you can use:

var publicKey = certificate.PublicKey.Key as RSACryptoServiceProvider;

var encryptedData = publicKey.Encrypt(<yourdata>, false);

这里,我没有使用 OAEP 进行加密,但是您可以通过将第二个参数的 fOAEP 设置为 true 来使用它

Here, i didn't use OAEP for encryption, but you can use it by setting the fOAEP to true for the second parameter.

要解密数据,可以使用:

To decrypt data, you can use:

var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;

var data = privateKey.Decrypt(encryptedData, false);

PFX中的证书可能没有相应的私钥,因此您可以使用以下属性在访问 PrivateKey 属性

A certificate in the PFX may not have a corresponding private key, so you can use the following property to check if the private key exists before accessing the PrivateKey property

if (!certificate.HasPrivateKey)
    throw new Exception("The certificate does not have a private key");

如果您已使用 OAEP 进行了加密,则必须使用设置为 true fOAEP 进行解密.

If you have encrypted with OAEP, then you have to decrypt with fOAEP set to true.

要签名数据,可以使用:

To sign data, you can use:

var signature = privateKey.SignData(<yourdata>, "SHA1");

要验证签名,可以使用:

To verify the signature, you can use:

var isValid = publicKey.VerifyData(<yourdata>, "SHA1", signature);

在这里,我使用了 SHA1 ,它不被认为是强大的.您可以使用其他更强大的哈希算法,例如 SHA256 .

Here i used SHA1 which is not considered strong. You can use other hashing algorithms like SHA256 which are stronger.

最后,如果您收到的消息是一个小字符串,那么前面的过程就可以了.但是,如果您要加密大数据,那么我建议您使用对称加密,然后使用公共密钥加密对称密钥.(请参见 X509Certificate2类作为完整示例.)

Finally, if you're message is a small string, then the previous procedure is fine. However, if you're encrypting large data, then i suggest that you use symmetric encryption and then encrypt the symmetric key with the public key. (See X509Certificate2 Class for full example.)

这篇关于如何使用.pfx证书进行加密,解密和签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 02:45