如何将 Aes.Key 转换为 secureString ?我正在做一个 byte[] -> string -> securestring。我面临着一个不同的问题。 将字节 [] 中的 key 转换为字符串并返回字节 [] 时,我得到一个不同的字节 []。代码有什么问题?
Aes aes = Aes.Create();
aes.GenerateIV();
aes.GenerateKey();
byte[] byteKey1 = aes.Key;
string sKey = Encoding.UniCode.GetString(byteKey);
byte[] byteKey2= Encoding.UniCode.GetBytes(sKey);
“byteKey1”和“byteKey2”有时是不同的。如果我使用 Encoding.Default,它们是相等的,但当不同的机器具有不同的默认编码时,它们会出现问题。
如何将 byte[] 中的 key 转换为 SecureString 并返回 byte[]?
谢谢。
最佳答案
切勿对加密 key 或密文等二进制数据使用文本编码(例如 Unicode 或 ASCII)。编码旨在用于文本表示,并且实现可以根据编码允许更改二进制内容。
相反,使用 Convert.ToBase64String
和 Convert.FromBase64String
将二进制文本转换为可以以文本格式编码的形式。
下面的代码将说明byteKey2
和byteKey
是相同的。
string sKey = Convert.ToBase64String(byteKey);
byte[] byteKey2= Convert.FromBase64String(sKey);
bool equal = byteKey.SequenceEqual(byteKey2); // will be true
关于c# - 在 C# 中将 Aes.Key 转换为 SecureString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24226664/