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

C# 在C中将Aes.Key转换为SecureString#,c#,encryption,bytearray,securestring,C#,Encryption,Bytearray,Securestring,如何将Aes.Key转换为secureString?我正在做一个byte[]->string->securestring。我面临着一个不同的问题。 当将字节[]中的键转换为字符串并返回到字节[]时,我会得到一个不同的字节[]。代码有什么问题 Aes aes = Aes.Create(); aes.GenerateIV(); aes.GenerateKey(); byte[] byteKey1 = aes.Key; string sKey = Encoding.UniCode.GetStri

如何将Aes.Key转换为secureString?我正在做一个byte[]->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,然后再转换回字节[]

谢谢。

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

相反,请使用和将二进制文本转换为可以以文本格式编码的形式

以下代码将说明
byteKey2
byteKey
将是相同的

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