gpt4 book ai didi

c# - 即使使用相同的 key ,加密输出也总是不同

转载 作者:太空狗 更新时间:2023-10-30 00:09:36 25 4
gpt4 key购买 nike

我正在尝试将密码存储在我想稍后检索的文件中。散列法不是一个选项,因为我以后需要连接到远程服务器的密码。

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

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;
}
}

最佳答案

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

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

关于c# - 即使使用相同的 key ,加密输出也总是不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/118599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com