2013-04-12 93 views
4

我正在開發一個項目,我需要使用「公鑰」來使用RSA算法加密郵件。我被提供了一個證書,我的第一個想法是使用該證書中的公鑰,並且在調查之後,我瞭解到我需要使用RSACryptoServiceProvider進行加密。從公鑰(不是證書)構造RSACryptoServiceProvider

我檢查了msdn,只有我以爲我應該使用的方法是RSACryptoServiceProvider.ImportCspBlob(byte[] keyBlob)。 當我試圖使用從證書導出的公鑰時,出現證書頭數據無效的錯誤。

我知道我可以將X509certificate2.PublicKey.Key轉換爲RSACryptoServiceProvider,但是從我的客戶所瞭解的情況來看,我將只會給予公鑰而不是證書。該密鑰必須保存在.xml配置文件中。

所以總結一下:有沒有一種方法可以在只給定證書的公鑰的情況下生成RSACryptoServiceProvider

回答

0

你可以嘗試看看下面這個例子: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; 
    } 
} 
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 "); 
    }