2016-07-28 138 views
0

我有一個問題,我怎麼能從Windows 2008服務器找到私鑰。用私鑰解密郵件RSA

首先我用加密的公鑰的數據,我提取從URL HTTPS 這樣的:

public static string Encrypt(string Data) 
    { 
     try 
     { 
      var Crypto = new RSACryptoServiceProvider(2048); 
      var RsaKeyInfo = Crypto.ExportParameters(false); 
      RsaKeyInfo.Modulus = PublicKeyByte(); 
      Crypto.ImportParameters(RsaKeyInfo); 

      var bytesData = Encoding.Unicode.GetBytes(Data); 
      var bytesCypherText = Crypto.Encrypt(bytesData, false); 
      var cypherText = Convert.ToBase64String(bytesCypherText); 

      return cypherText; 
     } 
     catch (Exception ex) 
     { 

      return null; 
     } 
    } 
    private static byte[] PublicKeyByte() 
    { 
     Uri u = new Uri("https:\\domain.com"); 
     ServicePoint sp = ServicePointManager.FindServicePoint(u); 

     string groupName = Guid.NewGuid().ToString(); 
     HttpWebRequest req = HttpWebRequest.Create(u) as HttpWebRequest; 
     req.ConnectionGroupName = groupName; 

     using (WebResponse resp = req.GetResponse()) 
     { 

     } 
     sp.CloseConnectionGroup(groupName); 
     return sp.Certificate.GetPublicKey(); ; 
    } 

現在我不知道如何解密的消息中提取在C#中的私鑰? ,我想知道這

感謝更多的信息,

+1

您無法從服務器提取私鑰,因爲這幾乎違背了使用此技術的目的。如果您有權訪問服務器,則可以接收密文並使用本地存儲在該服務器上的私鑰解密該消息。 – Glubus

+0

是的,我有權訪問服務器,我想在本地提取私鑰,我希望在我的程序中自動讀取私鑰。 –

+0

好吧,那麼實際問題是什麼呢?如果您使用的是Windows,則應將密鑰存儲在C:\ Users \ \ .ssh \之類的位置。只要通過你的服務器讀取文件(你說你有權訪問服務器,所以你應該能夠以編程方式添加這個)。 – Glubus

回答

0

我通過提取證書文件.PFX並使用System.Security.Cryptography.X509Certificates加密和解密IM解決了這個:

public static string Encrypt(string data) 
    { 
     try 
     { 
      var path = @"certificate.pfx"; 
      var password = "test"; 
      var collection = new X509Certificate2Collection(); 
      collection.Import(path, password, X509KeyStorageFlags.PersistKeySet); 
      var certificate = collection[0]; 
      var publicKey = certificate.PublicKey.Key as RSACryptoServiceProvider; 
      var bytesData = Convert.FromBase64String(data); 
      var encryptedData = publicKey.Encrypt(bytesData, false); 
      var cypherText = Convert.ToBase64String(encryptedData); 

      return cypherText; 
     } 
     catch (Exception ex) 
     { 

      return null; 
     } 
    } 
    public static string Decrypt(string data) 
    { 
     try 
     { 
      var path = @"certificate.pfx"; 
      var password = "test"; 
      var collection = new X509Certificate2Collection(); 
      collection.Import(path, password, X509KeyStorageFlags.PersistKeySet); 
      var certificate = collection[0]; 

      var privateKey = certificate.PrivateKey as RSACryptoServiceProvider; 
      var bytesData = Convert.FromBase64String(data); 
      var dataByte = privateKey.Decrypt(bytesData, false); 
      return Convert.ToBase64String(dataByte); 
     } 
     catch (Exception ex) 
     { 
      return ""; 
     } 
    }