Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding to use to convert Bytes array to String and vice-versa

I use this code to encrypt a string (basically, this is the example given on the Rijndael class on MSDN):

public static String AESEncrypt(String str2Encrypt, Byte[] encryptionKey, Byte[] IV)
{
    Byte[] encryptedText;

    using (RijndaelManaged rijAlg = new RijndaelManaged())
    {
        // Use the provided key and IV
        rijAlg.Key = encryptionKey;
        rijAlg.IV = IV;

        // Create a decrytor to perform the stream transform
        ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

        // Create the streams used for encryption
        using (MemoryStream msEncrypt = new MemoryStream())
        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
        {
            using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
            {
                // Write all data to the stream
                swEncrypt.Write(str2Encrypt);
            }

            encryptedText = msEncrypt.ToArray();
        }
    }

    return Encoding.Default.GetString(encryptedText);
}

I use Encoding.Default to convert a byte array to a string but I'm not sure it's a good solution. My goal is to store encrypted text (such as passwords...) in files. Should I continue with Encoding.Default or use Encoding.UTF8Encoding or something else?

Can that have negative consequences on the stored values when I try to encrypt and decrypt them if the files are moved onto different OS'?

like image 855
Otiel Avatar asked Nov 03 '11 14:11

Otiel


1 Answers

You should absolutely not use an Encoding to convert arbitrary binary data to text. Encoding is for when you've got binary data which genuinely is encoded text - this isn't.

Instead, use Convert.ToBase64String to encode the binary data as text, then decode using Convert.FromBase64String.

like image 52
Jon Skeet Avatar answered Oct 07 '22 20:10

Jon Skeet