3

我正在做一个项目,我需要使用“公钥”来使用 RSA 算法加密消息。我获得了证书,我的第一个想法是使用该证书中的公钥,经过调查,我了解到我需要RSACryptoServiceProvider用于加密。

我检查了 msdn,我认为我应该使用的唯一方法是RSACryptoServiceProvider.ImportCspBlob(byte[] keyBlob). 当我尝试使用从证书导出的公钥时,我收到一个错误,即证书的标头数据无效。

我知道我可以强制X509certificate2.PublicKey.Key转换,RSACryptoServiceProvider但从我的客户那里了解到的是,今后我将只获得一个公钥而不是证书。此密钥必须保存在 .xml 配置文件中。

总结一下:有没有办法只生成RSACryptoServiceProvider给定证书的公钥?

4

2 回答 2

1

你可以试试看这个例子:RSA public key encryption in C#

var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

var testData = Encoding.UTF8.GetBytes("testing");

using ( var rsa = new RSACryptoServiceProvider(1024))
{
    try
    {
        // client encrypting data with public key issued by server
        //
        rsa.FromXmlString(publicKey);
        var encryptedData = rsa.Encrypt(testData, true);

        var base64Encrypted = Convert.ToBase64String(encryptedData);

    }
    finally
    {
        rsa.PersistKeyInCsp = false;
    }
}
于 2015-11-09T22:15:42.020 回答
0

你很好,并且遵循一个很好的典型模式。数据的发送者不需要私钥。

以下可能会证实您已经弄清楚的一些代码。我为我遗漏的接收器/解码器设置私钥的那一行。我从我的构建部署内容中的一个测试用例中获取了这个。

 byte[] certBytAr;  // This is the certificate as bianry in a .cer file (no  private key in it - public only) 

 X509Certificate2 cert2 = new X509Certificate2(certBytAr);


 string strToEncrypt = "Public To Private Test StackOverFlow PsudeoCode. Surfs Up at Secret Beach.";
 byte[] bytArToEncrypt = Encoding.UTF8.GetBytes(strToEncrypt);

 RSACryptoServiceProvider rsaEncryptor = (RSACryptoServiceProvider)cert2.PublicKey.Key; 

 byte[] dataNowEncryptedArray = rsaEncryptor.Encrypt(bytArToEncrypt, true);

 // done - you now have encrypted bytes 
 // 

  // somewhere elxe ...
 // this should decrpyt it - simulate the destination which will decrypt the data with the private key 

 RSACryptoServiceProvider pk =   // how this is set is complicated 

 // set the private key in the x509 oobject we created way above 
 cert2.PrivateKey = pk; 

 RSACryptoServiceProvider rsaDecryptor = (RSACryptoServiceProvider)cert2.PrivateKey;
 byte[] dataDecrypted = rsaDecryptor.Decrypt(dataNowEncryptedArray, true);

 Console.WriteLine(" encrypt 1 Way Intermediate " + BitConverter.ToString(dataDecrypted));

 string strDecodedFinal = Encoding.UTF8.GetString(dataDecrypted);

 if (strDecodedFinal == strToEncrypt)
 {

 }
 else
 {
     Console.WriteLine(" FAILURE OF  ENCRYPTION ROUND TRIP IN SIMPLE TEST (Direction: Public to Private). No Surfing For You ");
  }
于 2015-11-10T00:29:03.143 回答