Password Protected Stream Using Decorator Pattern

Computer/Software Security

Are you in love with ‘Design Patterns” and “Software Security”? If yes, then this article is for you.

Computer/Software Security
Image by TheDigitalWay from Pixabay

This article explains how to build a Password Protected Stream on top of System.IO.Stream using decorator pattern. The stream can then be used as a normal stream, with slight changes in usage.

This work is just a part of my exercise that I was doing while reading the book titled ‘C# 3.0 Design Patterns’ by ‘Judith Bishop’. It is an exercise of the section ‘Decorator Patterns’. I opted to make it a bit complex and more functional rather than just a simple one for the sake of an exercise.

Logical Parts

The code has four logical parts:

    1. The PasswordProtectedStream class that extends System.IO.Stream and overrides several required properties of the Stream class. The main points of interest are how I have overridden the read and write methods of Stream.
    2. The ‘DataEnvelop‘ class that is marked as ‘Serializable‘ and it is the actual place holder for the data. This class is serialized to a class file using ‘BinaryFormatter‘. To keep the code simpler, I have saved the data as plain text otherwise for a more real world scenario, encryption can be applied or another stream can be extended as ‘EncryptedStream‘ using the same ‘Decorator Pattern’ technique.
    3. A delegate ‘ReadCompleteHandler‘ and a corresponding event ‘On_ReadComplete‘. This event passes the data to the client application after verifying the password. I couldn’t make the data available directly from the read method as the data to be read was more in length than the actual data (because of serialization). So this technique is used. However, I would request the readers if anyone can help me erase the delegate and make the data available in the buffer directly by resetting the position and length of data to be read.
    4. A class ‘ReadCompleteEventArgs‘ that is a parameter to the event ‘On_ReadComplete‘ and passes the read status and data to the client application.

Code Workflow

The whole code works according to the flow below:

    1. You create an instance of PasswordProtectedStream with two arguments: A base stream and a password.
    2. You put this stream into a StreamReader or StreamWriter.
    3. If you put it in StreamWriter, it will call the overridden ‘Write‘ method of the PasswordProtectedStream. This method will create an instance of a serializable object of the class ‘DataEnvelop‘ and put the password in that object along with data and write it on the actual stream.
    4. If you put it in StreamReader, the overridden ‘Read‘ method is called for PasswordProtectedStream. It works slightly different than the usual way of how streams read. It will read all the bytes(including the headers also for the serialized object DataEnvelop), check the password and it is correct, will pass the data to the ‘On_ReadComplete‘ event for processing by the client application. This is done using ‘ReadCompleteEventArgs‘ class. Else if the password is wrong, no data is passed to the event and only failed status is reported so that it can be caught in the client application. The status is marked by an enum named ‘Status‘.

Shortcomings

Since this is the first version, so the code works fine on single reads and single writes. However it is likely to have problems on multiple reads and multiple writes. This issue can be resolved if anyone can suggest a way where I don’t have to use delegates and events and can directly reset the buffer in the Read method of the stream. I tried it but it was looping forever due to some seeking and positioning problems and also due to the length of the buffer having a chunk of 1024 bytes. All suggestions would be most welcome.

Entire Source Code

//extends the stream class
public class PasswordProtectedStream : Stream
{
    string password; //password for the stream
    Stream str; //the base stream

    //this is a kind of locking variable so that if read operations are called
    //multiple times, the event (the description to be followed) doesn’t get
    //invoked multiple times
    bool eventRaised = false; 

    //delegate for event
    public delegate void ReadCompleteHandler (object s, ReadCompleteEventArgs e); 

    // event that passes data and read status to the client application
    public event ReadCompleteHandler On_ReadComplete; 

    //set the base parameters
    public PasswordProtectedStream(Stream str, string password)  : base() 
    {
        this.str = str;
        this.password = password;
    }

    #region "Overridden Methods of Stream"
    //override the write method
    public override void Write(byte[] buffer, int offset, int count)
    {
        byte[] data = new byte[count];
        
        for (int i = offset, j = 0; j < count; i++, j++)
            data[j] = buffer[i]; //construct the actual data buffer

        //create an instance of our own custom serialized class (to be followed
        //later)
        DataEnvelop env = new DataEnvelop(data, password); 
        BinaryFormatter f = new BinaryFormatter();
        f.Serialize(str, env); //serialize the object
    }
    
    //override the read method
    public override int Read(byte[] buffer, int offset, int count)
    {
        //read all bytes from base stream
        int r = str.Read(buffer, offset, count);
        
        //construct buffer to hold actual data and not the default buffer
        //otherwise the object won’t be de-serialized properly due to padded empty
        //bytes
        byte[] newData = new byte[str.Length]; 

        //in respect to the actual length of the base stream
        for (int i = 0; i < str.Length; i++) 
            newData[i] = buffer[i]; //copy all non-empty bytes

        //construct memory stream for de-serialization
        MemoryStream mstr = new MemoryStream(newData); 

        BinaryFormatter f = new BinaryFormatter();
        DataEnvelop env = (DataEnvelop)f.Deserialize(mstr);

        if (env.password == password) //if password is matched
        {
            //if event is not empty and it’s not been invoked earlier
            if (On_ReadComplete != null && !eventRaised) 
            {
                On_ReadComplete(this, new ReadCompleteEventArgs (ReadCompleteEventArgs.Status.SUCCESS, env.data)); //bind successful read event

                eventRaised = true; //mark it so that the event is not invoked again on multiple reads
            }
        }
        else //if wrong password
        {
            if (On_ReadComplete != null && !eventRaised) //if event is not empty and it’s not been invoked earlier
            {
                On_ReadComplete(this, new ReadCompleteEventArgs (ReadCompleteEventArgs.Status.FAILURE, null)); //bind un-successful read event

                eventRaised = true; //mark it so that the event is not invoked again on multiple reads
            }
        }

        //return actual number of bytes read and not the bytes of the actual
        //data otherwise it will loop. This is the only reason why I had to pass
        //the data to the event and couldn’t directly process here. If anyone can
        //suggest a way, I would be grateful.
        return r; 
    }

    public override void Close()
    {
        str.Close();
        str.Dispose();
    }
    #endregion

    #region "Overridden Properties of Stream"
    public override void SetLength(long value)
    {
        str.SetLength(value);
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        return str.Seek(offset, origin);
    }

    public override long Position
    {
        get { return str.Position; }
        set { str.Position = value; }
    }

    public override long Length
    {
        get { return str.Length; }
    }

    public override bool CanWrite
    {
        get { return str.CanWrite; }
    }

    public override void Flush()
    {
        str.Flush();
    }

    public override bool CanSeek
    {
        get { return str.CanSeek; }
    }

    public override bool CanRead
    {
        get { return str.CanRead; }
    }

    #endregion

    //private DataEnvelop Class that is serialized to the base stream with the
    //password and the data bytes, it can be enhanced to encrypt the password
    [Serializable]
    class DataEnvelop 
    {
        public byte[] data { get; set; }
        public string password { get; set; }
        
        public DataEnvelop(byte[] data, string password)
        {
            this.data = data;
            this.password = password;
        }
    }
    
    //arguments passed to the event that passes data to the client
    public class ReadCompleteEventArgs : EventArgs
    {
        byte[] data; //actually data bytes
        
        //status of the current output, whether password is correct or not
        Status status;
    
        //if password is correct, set as CORRECT else FAILURE
        public enum Status { SUCCESS, FAILURE }
    
        public ReadCompleteEventArgs(Status status, byte[] data)
        {
            this.data = data;
            this.status = status;
        }
        
        public byte[] Data { get { return data; } }
        public Status ReadStatus { get { return status; } }
    }
}

//This is the client code. You can place two buttons named button1 and button2 and
//place the following code in the forms code section
private void button1_Click(object sender, EventArgs e)
{
    PasswordProtectedStream st = new PasswordProtectedStream
    (new FileStream("C:/pwdsample.txt", FileMode.Create), "12345"); //create instance of our stream
    
    StreamWriter w = new StreamWriter(st);
    w.Write("Hye this is test"); //write some data
    w.Flush();
    w.Close();
    st.Close();
    st.Dispose();
    MessageBox.Show("Data Written Successfully");
}

private void button2_Click(object sender, EventArgs e)
{
    //create instance of our stream, try changing a password here
    PasswordProtectedStream st = new PasswordProtectedStream(new FileStream ("C:/pwdsample.txt", FileMode.Open), "12345");
    
    st.On_ReadComplete += new PasswordProtectedStream.ReadCompleteHandler (st_On_ReadComplete); //hook the read complete event
    
    StreamReader w = new StreamReader(st);
    
    //Read but don’t display the data here, else you won’t get anything useful.
    //Readers are welcome if they can provide an implementation which enables us
    //to read the data in usual manner, without the use of event
    w.ReadToEnd();
    
    w.Close();
    st.Close();
    st.Dispose();
}

void st_On_ReadComplete (object s, PasswordProtectedStream.ReadCompleteEventArgs e)
{
    if (e.ReadStatus == PasswordProtectedStream.ReadCompleteEventArgs.Status.FAILURE) //if wrong password

        MessageBox.Show("Wrong Password");
    else
        MessageBox.Show("Data Read back: " + Encoding.ASCII.GetString(e.Data)); //display data
}

Download Source Code Here

You can also view this article at CodeProject, written by me.

Related Posts...
Are you planning to buy an economical tablet? Then you have landed on the right
Music and computers are two different branches of study yet mathematics links them. See for
Learn different object changes from VB 6 to VB.NET in this article.
Performing file-system operations work similar in Java across platforms but differ in VB for Windows.
Exception handling is a necessary element of coding. Compare the process and methods of exception
Want to learn networking programming techniques? This article describes the differences and approaches of network
Database Access is a very important aspect of programming. Learn how to do write database
Object serialization is useful for transfer of data across heterogeneous protocols. Learn its implementation in
Without reporting, any data centric program is incomplete. Learn how to use crystal reports (one