用于将Bytes数组转换为String的编码,反之亦然 [英] Encoding to use to convert Bytes array to String and vice-versa
问题描述
我使用这个代码加密一个字符串(基本上,这是在 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 将任意二进制数据转换为文本。 编码
是用于当您具有真正被编码的文本的二进制数据时 - 这不是。
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.
,请使用 Convert.ToBase64String
将二进制数据编码为文本,然后使用 Convert.FromBase64String
。
Instead, use Convert.ToBase64String
to encode the binary data as text, then decode using Convert.FromBase64String
.
这篇关于用于将Bytes数组转换为String的编码,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!