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().