Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

c# - 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'?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...