即使使用相同的密钥,加密输出也总是不同
时间:2020-03-06 14:34:33 来源:igfitidea点击:
我正在尝试将密码存储在一个文件中,以供以后检索。散列不是一种选择,因为我需要密码才能稍后连接到远程服务器。
以下代码运行良好,但是即使键相同,每次也会创建不同的输出。这很糟糕,因为当应用程序关闭并重新启动时,我将无法再检索密码。如何将密码存储在文件中并在以后检索?
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"中执行此操作。
根据CreateEncryptor的文档:
If the current IV property is a null reference (Nothing in Visual Basic), the GenerateIV method is called to create a new random IV.
这将使密文每次都不同。
注意:这里讨论一种解决方法,我建议我们可以在mac前面加上明文...那么密文的第一个块实际上是IV,但都是可重复的
即使生成一个随机数,也需要指定一个IV(初始化向量)。如果我们使用随机IV,则必须将其与密文一起存储,以便以后在解密时使用它,或者可以从其他一些数据派生IV(例如,如果我们正在加密密码,则可以从以下密码派生IV)用户名)。

