简体   繁体   中英

Convert Aes.Key to SecureString in C#

How do I convert Aes.Key to a secureString ? I am doing a byte[] -> string -> securestring. I am facing a different problem. When converting the key, in byte[], to string and back to byte[] I get a different byte[]. What is the problem with the code ?

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" and "byteKey2" are sometimes different. They are equal if I use Encoding.Default but that has problems when different machines have different default encoding.

How do I convert the Key in byte[] to SecureString and back to byte[] ?

Thanks.

Never use text encoding (eg, Unicode or ASCII) on binary data like a cryptographic key or ciphertext. Encoding is intended for textual representations, and the implementation can change the binary contents as permitted by the encoding.

Instead, use Convert.ToBase64String and Convert.FromBase64String to convert binary text into a form that can be encoded in a textual format.

The following code will illustrate byteKey2 and byteKey will be identical.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM