我正在尝试直接写入加密流,然后将其存储到文件中。
我有下面的代码,但是当我解密时,我得到垃圾而不是我正在加密的消息。
任何人都可以帮助我在下面的代码中遗漏的内容吗?
static void Main(string[] args)
{
string password = "pswd";
string fileName = "test.txt";
string msg = "Secret Message";
FileEncryptionExample fe = new FileEncryptionExample();
fe.EncryptFileExample(fileName, password, msg);
fe.DecryptFileExample(fileName, password);
Console.WriteLine("Press any key...");
Console.ReadKey();
}
//------------------------------------------------------------------
public class FileEncryptionExample
{
public void DecryptFileExample(string fileName, string password)
{
byte[] salt = Encoding.ASCII.GetBytes(password.Length.ToString());
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(password, salt);
RijndaelManaged rm = new RijndaelManaged();
CryptoStream strm = new CryptoStream(fs, rm.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)), CryptoStreamMode.Read);
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
byte[] data = new byte[12];
sr.Read(data, 0, 12);
Console.WriteLine(sr.ReadLine());
}
}
}
}
public void EncryptFileExample(string fileName, string password, string text)
{
StreamWriter sw = new StreamWriter(fileName);
byte[] salt = Encoding.ASCII.GetBytes(password.Length.ToString());
using (RijndaelManaged rm = new RijndaelManaged())
{
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(password, salt);
using (CryptoStream strm = new CryptoStream(sw.BaseStream, rm.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)), CryptoStreamMode.Write))
{
//sw.WriteLine(text);
byte[] data = Encoding.ASCII.GetBytes(text);
strm.Write(data, 0, data.Length);
}
}
}
}
答案 0 :(得分:2)
char[]
,但您传递的是byte[]
。fs
传递给StreamReader,而不是strm
。您可以使用:
public void DecryptFileExample(string fileName, string password)
{
byte[] salt = Encoding.ASCII.GetBytes(password.Length.ToString());
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(password, salt);
RijndaelManaged rm = new RijndaelManaged();
CryptoStream strm = new CryptoStream(fs, rm.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)), CryptoStreamMode.Read);
using (StreamReader srDecrypt = new StreamReader(strm))
{
var str = srDecrypt.ReadToEnd();
Console.WriteLine(str);
}
}
}
同样作为一个FYI - 你的盐非常不安全。有关详细信息,请参阅here。