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'?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With