2016-04-22 86 views
1

我在C++中創建服務器端程序,程序使用openssl庫創建RSA公鑰和私鑰,然後通過網絡爲客戶端分配公鑰。在客戶端我寫了c#程序先獲取公鑰然後加密數據。但我無法將公鑰添加到RSACryptoServiceProvider。將openssl公鑰導入C#RSACryptoServiceProvider

有沒有辦法將RSA公鑰導入RSACryptoServiceProvider?

----- BEGIN RSA公鑰----- MIIBCAKCAQEAsgVkBAQPdtRtICOqWdZ0ZiMAb9UvUX0BaxANN22bL5RzTJAL + PMG QKaA61B1m0NPOjdIIXMwkaAzXOmzuNwKm2Ugb8jO15B6ovAhe73jAoltFFdi10Te zCJgT8/xLAWt1mOXCAK9vD4Pv5LMN76BF + YjEVvylQ3l87255ElZrP4UluCGj0U3 uczW8 + Cqao3QoL6xSxPU9jSK0FT/OhAL312cAXYbnaiJH + wAf1kkv4ez28XAlFId MlCmh2n8YSuxk1GdOXaps8IoluDzmHeQ8vk2quQMPpFXzfCayBoPm9lVPOjOQkAH 8ClJda0Uy052N5aE0BuyX1KRxOSdRRKk9wIBAw ==

- ---結束RSA公共密鑰-----

+0

這是否Project幫助:https://github.com/openssl-net/openssl-net –

回答

1

您可以使用此功能BouncyCastle,不幸的是,這是解決這個問題的唯一方法之一。

PemReader reader = new PemReader(new StreamReader(File.Open(file, FileMode.Open))); 
AsymmetricCipherKeyPair = (AsymmetricCipherKeyPair)reader.ReadObject(); 
reader.Reader.Close(); 

此代碼未經過測試,所以某些方法名稱可能有點偏差。然後,您可以使用DotNetUtilities類中的靜態方法轉換爲RSACryptoServiceProvider

+0

非常感謝。非常好的圖書館。 – Khalil

1

這是一個示例代碼顯示瞭如何RSA公共密鑰添加到的RSACryptoServiceProvider在C#

public Stream GenerateStreamFromString(string s) 
{ 
    MemoryStream stream = new MemoryStream(); 
    StreamWriter writer = new StreamWriter(stream); 
    writer.Write(s); 
    writer.Flush(); 
    stream.Position = 0; 
    return stream; 
} 

string publicKey = "-----BEGIN RSA PUBLIC KEY-----\nMIIBCAKCAQEAoNhWLaL11Zy4L6Cp2IDFv2JGnPkoRnFrKTy5b23uszzbSammdIwi\n6Wtr/7Zg3wmqlwt/yhH4F6rwSysB04xvMnWjuRsw2Kz4u7FHMPlgrIObGDFqcEms\nllNTA8xSWh/+TPfxWdAN5bpUwLYo6Mizl+VStL4CtVQFS8/mQSUnCju3csfxNGlk\nPQdbwZWB/5DdswrhkUcob8wl3bCCZCz3zWzMNJFTgTEiZQr+qTtuY7ST+fmpO33r\nDJoboysiGPKUkQixKcG2s1jJJkQircAHkmiQPS6PlUapNahFNaPa3rh1zR4l5NN6\nxWudPYQhZ8VvD4C8eT2bfrUlsikAyXIX4QIBAw==\n-----END RSA PUBLIC KEY-----\n" 
using (Stream stream = GenerateStreamFromString(publicKey)) 
{ 

     PemReader pemReader = new PemReader(new StreamReader(stream)); 
     AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter)pemReader.ReadObject(); 
     pemReader.Reader.Close(); 
     Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters rsaPub = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)publicKey; 

     RSAParameters RSAKeyInfo = Org.BouncyCastle.Security.DotNetUtilities.ToRSAParameters(rsaPub); 

     RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048); 
     RSA.ImportParameters(RSAKeyInfo); 

     byte[] encryptedData = RSA.Encrypt(plainText, true); 
}