2008-09-23 54 views
4

我試圖將密碼存儲在我想稍後檢索的文件中。哈希不是一個選項,因爲我需要稍後連接到遠程服務器的密碼。即使使用相同的密鑰,加密輸出始終不同

以下代碼運行良好,但每次都會創建不同的輸出,即使密鑰相同。這很糟糕,因爲應用程序關閉並重新啓動時,我將無法再檢索我的密碼。如何將密碼存儲在文件中並在以後檢索它們?

public class EncyptDecrypt { 

    static System.Security.Cryptography.TripleDESCryptoServiceProvider keyProv = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); 

    public static System.Security.Cryptography.TripleDESCryptoServiceProvider KeyProvider { 
     get { 
      keyProv.Key = new byte[] { /* redacted with prejudice */ }; 
      return keyProv; 
     } 
    } 

    public static string Encrypt(string text, SymmetricAlgorithm key) { 

     if (text.Equals(string.Empty)) return text; 

     // Create a memory stream. 
     MemoryStream ms = new MemoryStream(); 

     // Create a CryptoStream using the memory stream and the 
     // CSP DES key. 
     CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write); 

     // Create a StreamWriter to write a string 
     // to the stream. 
     StreamWriter sw = new StreamWriter(encStream); 

     // Write the plaintext to the stream. 
     sw.WriteLine(text); 

     // Close the StreamWriter and CryptoStream. 
     sw.Close(); 
     encStream.Close(); 

     // Get an array of bytes that represents 
     // the memory stream. 
     byte[] buffer = ms.ToArray(); 

     // Close the memory stream. 
     ms.Close(); 

     // Return the encrypted byte array. 
     return System.Convert.ToBase64String(buffer); 
    } 

    // Decrypt the byte array. 
    public static string Decrypt(string cypherText, SymmetricAlgorithm key) { 

     if (cypherText.Equals(string.Empty)) return cypherText; 

     string val; 

     try { 
      // Create a memory stream to the passed buffer. 
      MemoryStream ms = new MemoryStream(System.Convert.FromBase64String(cypherText)); 

      // Create a CryptoStream using the memory stream and the 
      // CSP DES key. 
      CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read); 

      // Create a StreamReader for reading the stream. 
      StreamReader sr = new StreamReader(encStream); 

      // Read the stream as a string. 
      val = sr.ReadLine(); 

      // Close the streams. 
      sr.Close(); 
      encStream.Close(); 
      ms.Close(); 
     } 
     catch (System.Exception) { 

      return string.Empty; 
     } 

     return val; 
    } 
} 

回答

8

我相信發生的事情是密碼提供者是隨機產生一個IV。指定這個,它不應該有所不同。

編輯:您可以通過設置IV屬性在'keyProvider'中執行此操作。

+0

作爲說明,IV是與您的密鑰一起附加的一段數據。這些信息是公開的,不需要隱藏,如果是安全的話,也不會增加安全性。它被用來使密碼分析變得更加困難。 – 2008-09-23 01:27:59

3

根據CreateEncryptor的文檔:

如果當前的IV特性是空 引用(在Visual Basic中爲Nothing), 的GenerateIV方法被調用來 創建一個新的隨機IV。

這會使密文每次都不同。

注:解決的辦法是討論here,我建議你可以與Mac前面加上明文......然後是密文的第一個塊是有效的IV,但它的所有重複

2

你需要指定一個IV(初始化矢量),即使你生成一個隨機的。如果您使用隨機IV,那麼您必須將其與密文一起存儲,以便您稍後可以在解密時使用它,或者您可以從其他一些數據中派生IV(例如,如果您正在加密密碼,則可以從中導出IV用戶名)。

相關問題