String Stream for .NET

I was working with C++ Standard Template Library (STL) library and when using the StringStream class I felt like we need this for .NET :) Yes we have a great class StringBuilder but we can’t use it as a Stream (because it is not).

Most of the cryptographic classes works with the stream object. I wanted to save the encrypted information as text. Ideally we could use memoryStream but it is not really efficient, because it is bits and we need to build a model for serializing/deserializing as text.

String Stream class (as I call it) is just an ugly but functional wrapper around StringBuilder class as shown some snippets below. I just wanted it to use with encryption and decryption a string. So only the functions needed is there which is enough to use. But I doubt it leaks a little, so use with care if needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class StringStream : Stream
{
        private StringBuilder strBuilder;
        public StringStream()
        {            strBuilder = new StringBuilder();        }

        public StringStream(string str)
        {            strBuilder = new StringBuilder(str);        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int howMuchRead = 0;
            for (int i = offset; i < count; i++)
            {
                var actualIndex = i * 2;                
                howMuchRead = i+1;
                if (actualIndex >= strBuilder.Length) 
                {
                    howMuchRead = count;
                    break;
                }                                   
                string s = strBuilder[actualIndex].ToString() + strBuilder[actualIndex + 1].ToString();
                buffer[i] = Convert.ToByte(s,16);
            }
            return howMuchRead;
        }
      public override void Write(byte[] buffer, int offset, int count)
        {            
            for (int i = offset; i < count; i++)
            {
                strBuilder.Append(buffer[i].ToString("x2"));
            }
        }
}

http://www.codingday.com;//downloads/StringStream.cs;StringStream;

The main magic is happening on reading and writing. each byte is represented as 2 characters in the string. It is using the helper function Convert.ToByte to make it happen. In the next post I will use it with a symmetric encryption helper class.