在C#中将Aes.Key转换为SecureString

时间:2014-06-15 04:49:52

标签: c# encryption bytearray securestring

如何将Aes.Key转换为secureString?我正在做一个字节[] - > string - > SecureString的。我面临着另一个问题。 将字符串转换为字符串[],字符串并返回字节[]时,我得到一个不同的字节[]。代码有什么问题?

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它们是相同的,但是当不同的机器具有不同的默认编码时会出现问题。

如何将字符[]中的密钥转换为SecureString并返回字节[]?

感谢。

1 个答案:

答案 0 :(得分:4)

切勿对二进制数据(如加密密钥或密文)使用文本编码(例如,Unicode或ASCII)。编码用于文本表示,实现可以在编码允许的情况下更改二进制内容。

相反,请使用Convert.ToBase64StringConvert.FromBase64String将二进制文本转换为可以文本格式编码的表单。

以下代码将说明byteKey2byteKey将完全相同。

string sKey = Convert.ToBase64String(byteKey);
byte[] byteKey2= Convert.FromBase64String(sKey);
bool equal = byteKey.SequenceEqual(byteKey2); // will be true