Roundtripping Encrypted Data Through Text

This question comes up every so often on the public newsgroups, so I thought I'd write out an explanation here.  When you try to round trip encrypted data through plain text (for instance, take the encrypted data and put it into a text string), you need to make sure that you preserve all the bits of the ciphertext, or else you will not be able to decrypt it again.  Many people try to use System.Text.Encoding.ASCII.GetString(cipherBytes) in order to get a printable string, but this will not work.  ASCII encoding uses only 7 bits, so the high order bit of each byte will be discarded.  Obviously this will prevent decryption from working properly on the data.

When putting ciphertext into a string you have two choices in general.  The first one is to use an encoding that uses all eight bits of a byte, for instance System.Text.Encoding.UTF8.  Note however that this will not (in general), produce a printable string.  Since all eight bits are in use, you could (and will) get bytes like 0x00 and 0x01, which are valid encrypted data but not printable on the display.  If you're looking to save the ciphertext into a text file, email, or XML document, you need to encode it in some way that ensures there are only printable characters in the string.  This is accomplished by base64 encoding the data, using the System.Convert.ToBase64String() method.

Basically, when I see this question, my advice is to convert the ciphertext to a base64 string using Convert.ToBase64(), and to retrieve the original ciphertext using Convert.FromBase64().

Comments (2)

  1. Arun P. Nair says:

    I have used a TripleDES encrypted connection string which return a byte array and used System.Text.Encoding.GetString to retrieve the printable string. On decryption, an error was shown – "Lengh of the data to encrypt is invalid."

    I’m putting my code below. Please comment on the code.

    private void EncryptConnectionString()


               byte[] bConnectionString = EncryptorDecryptor.Encrypt(this.txtPlainKey.Text);

               this.txtCipherKey.Text = System.Text.Encoding.Unicode.GetString(bConnectionString);

               this.txtCipherKey.Text = EncryptorDecryptor.Decrypt(System.Text.Encoding.Unicode.GetBytes(this.txtCipherKey.Text));


    When I used Convert.ToBase64string, decryption worked fine. I’m still confused because when I used the Text.Unicode.GetString and Text.Unicode.GetBytes on my connection string without encryption it has given the exact printable string.

  2. The Encoding class is not to be used to convert arbitrary bytes into a string; for that you need to use the Convert.ToBase64String method.  See for more details.


Skip to main content