编码使用字节数组转换为字符串,反之亦然 [英] Encoding to use to convert Bytes array to String and vice-versa
问题描述
我用这个code加密字符串(基本上,这是对的 MSDN上 Rijndael的类):
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);
}
我用 Encoding.Default
字节数组转换为字符串,但我不相信这是一个很好的解决方案。我的目标是存储加密的文本(如密码......)在文件中。我是否应该继续与 Encoding.Default
或使用 Encoding.UTF8Encoding
或其他什么东西?
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'?
推荐答案
您应该的绝对不会的使用的Encoding 以任意的二进制数据转换为文本。 编码
是当你得到的二进制数据这是真正带codeD文本 - 这不是
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.
相反,使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.convert.tobase64string.aspx\"><$c$c>Convert.ToBase64String$c$c>为en code中的二进制数据,文本,然后去code。使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx\"><$c$c>Convert.FromBase64String$c$c>.
这篇关于编码使用字节数组转换为字符串,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!