6

我正在尝试通过子类化 StreamReader 创建一个解密的文件流读取器(DFSR)类,这样我就可以将带有加密信息的文件名传递给它的(DFSR)构造函数,并返回我可以调用 StreamReader 的 ReadLine 方法的 streamReader。

我知道如何做如下,但我不知道如何将它重构为一个以 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);
                }
            }

        }
    }

}
4

1 回答 1

0

您可以使用构造函数中的静态方法来生成类似于以下内容的加密流:

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);
            }
        }
于 2013-07-04T19:04:08.027 回答