2008-09-23 82 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用户名)。

相关问题