tags:

views:

267

answers:

2

I have a .NET string which is Base64 encoded representation of an array of encrypted bytes. It is produced like this:

String Encrypt( String message )
{
    CryptoStream cryptostream = ...
    StreamWriter stream = new StreamWriter( cryptostream );
    ...
    return Convert.ToBase64String( ... );
}

Now I want a decryption function like

String Decrypt( String cypher )
{
    TextReader reader = new StringReader( cypher );
    byte[] buffer = new byte[ cypher.Length ];
    for( int i = 0; i < cypher.Length; ++i )
    {
        buffer[ i ] = (byte) reader.Read();
    }
    FromBase64Transform transformer = new FromBase64Transform();
    MemoryStream raw = new MemoryStream
    ( 
        transformer.TransformFinalBlock( buffer, 0, buffer.Length )
    );
    ...
}

Is there a way to use FromBase64Transform directly with CryptoStream (as the .NET documentation suggests), instead of manually converting the string to bytes, then manually decoding the bytes, and finally decrypting the decoded bytes?

A: 

There is no public built-in way to stream from a string, as of .NET 3.5.

You can implement a simple StringStream class that inherits from Stream, which will free you from having to convert the string to an array of bytes.

Jerome Laban
+1  A: 

I always the the Convert class to convert the string into an array of Byte.

An example:

    public static string DeCryptString(string s) {
        byte[] b = System.Convert.FromBase64String(s);

        using (MemoryStream ms = new MemoryStream(b)) 
        using (CryptoStream cs = /* Create decrypting stream here */)
        using (StreamReader sr = new StreamReader(cs)) {
            string buf = sr.ReadToEnd();
            return buf;
        }
    } // DeCryptString
GvS
Actually, the memory stream can be initialized directly using the byte array returned by Convert in this example. This avoids calls to Write and Seek.
Jerome Laban
@Jerome, thx, I've edited the example according your tip. Reading it back, I don't even know why I did it the complicated way.
GvS