即使使用相同的密钥,加密输出也总是不同

Vin*_*cio 4 c# encryption cryptography

我正在尝试将密码存储在我想要检索以供日后使用的文件中.Hashing不是一个选项,因为我需要密码才能连接到远程服务器以供日后使用.

以下代码运行良好,但每次创建不同的输出,即使键是相同的.这很糟糕,因为当应用程序关闭并重新启动时,我将无法再检索到我的密码.如何将密码存储在文件中并在以后检索?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*ous 8

我相信正在发生的事情是加密提供者正在随机生成一个IV.指定它,它应该不再有所不同.

编辑:您可以通过设置IV属性在"keyProvider"中执行此操作.

  • 手动指定IV也(通常)是一个坏主意.使用相同的IV加密多个明文是个坏主意.为什么同一明文的输出始终相同很重要? (2认同)