子类StreamReader来创建解密文件流读取器
本文关键字:读取 文件 解密 StreamReader 创建 子类 | 更新日期: 2023-09-27 18:21:08
我正试图通过将StreamReader子类化来创建一个解密的文件流读取器(DFSR)类,这样我就可以将带有加密信息的文件名传递给它的(DFSR)构造函数,并与StreamReader一起返回,我可以调用StreamReader的ReadLine方法。
我知道如何按照下面的方式进行,但我不知道如何将它折射到一个以StreamReader为父类的类中。
using (Rijndael rijAlg = Rijndael.Create())
{
rijAlg.Key = DX_KEY_32;
rijAlg.IV = DX_IV_16;
// Create a decrytor to perform the stream transform.
using (FileStream fs = File.Open("test.crypt", FileMode.Open))
{
using (CryptoStream cs = new CryptoStream(fs, rijAlg.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
}
您可以使用构造函数中的静态方法来生成类似于以下内容的加密流:
public class EncryptingFileStream : System.IO.StreamReader
{
public EncryptingFileStream(string fileName, byte[] key, byte[] IV)
: base(GenerateCryptoStream(fileName, key, IV))
{
}
private static System.IO.Stream GenerateCryptoStream(string fileName, byte[] key, byte[] IV)
{
using (System.Security.Cryptography.Rijndael rijAlg = System.Security.Cryptography.Rijndael.Create())
{
rijAlg.Key = key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
using (System.IO.FileStream fs = System.IO.File.Open(fileName, System.IO.FileMode.Open))
{
return new System.Security.Cryptography.CryptoStream(fs, rijAlg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);
}
}
}
}
使用此类:
using (EncryptingFileStream fs = new EncryptingFileStream("test.crypt", DX_KEY_32, DX_IV_16))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = fs.ReadLine()) != null)
{
Console.WriteLine(line);
}
}