Subclass StreamReader for creating a decrypted file stream Reader

I am trying to create a decrypted file stream class (DFSR) by subclassing StreamReader so that I can pass the file name using encrpyted info to its constructor (DFSR) and return using streamReader, which I can call with the ReadLine StreamReader method.

I know how to do this, as shown below, but I don’t know how to refract it in a class with StreamReader as the parent class.

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); } } } } } 
+6
source share
1 answer

You can use the static method from the constructor to generate a crypto stream similar to the following:

 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); } } } } 

To use this class:

  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); } } 
0
source

Source: https://habr.com/ru/post/948736/


All Articles