我是 C# 和密码学的新手,我通过从CodeProject和StackOverflow等各种来源获取数据来编写以下代码。
public class CryptoSafe
{
private const int SaltSize = 8;
public void EncryptAndWrite(FileInfo targetFile, string password)
{
FileStream stream = new FileStream(targetFile.FullName, FileMode.Open, FileAccess.Write);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
//
var keyGenerator = new Rfc2898DeriveBytes(password, SaltSize);
var rijndael = Rijndael.Create();
var length = rijndael.BlockSize;
// BlockSize, KeySize in bit --> divide by 8
cryptic.IV = keyGenerator.GetBytes(rijndael.BlockSize / 16);
cryptic.Key = keyGenerator.GetBytes(rijndael.KeySize / 32);
CryptoStream crStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write);
byte[] data = ASCIIEncoding.ASCII.GetBytes(System.DateTime.Now.ToString("dd-MMM-yyyy HH;mm:ss"));
crStream.Write(data, 0, data.Length);
crStream.Close();
stream.Close();
}
public string DecryptAndRead(FileInfo sourceFile, string password)
{
FileStream stream = new FileStream(sourceFile.FullName, FileMode.Open, FileAccess.Read);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
// read salt
//var fileStream = sourceFile.OpenRead();
//var salt = new byte[SaltSize];
// fileStream.Read(salt, 0, SaltSize);
// initialize algorithm with salt
var keyGenerator = new Rfc2898DeriveBytes(password, SaltSize);
var rijndael = Rijndael.Create();
cryptic.IV = keyGenerator.GetBytes(rijndael.BlockSize / 16);
cryptic.Key = keyGenerator.GetBytes(rijndael.KeySize / 32);
// decrypt
CryptoStream crStream = new CryptoStream(stream, cryptic.CreateDecryptor(), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(crStream);
string data = reader.ReadToEnd();
reader.Close();
stream.Close();
return data;
}
}
加密进展顺利,正在写入文件中。但是,在解密文件时它给出了错误“坏数据”。我尝试在 SO 上搜索它,但没有太大帮助。
我究竟做错了什么?请帮忙!