Search code examples
c#encryptionarrayssecurestring

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.


Solution

  • Never use text encoding (e.g., 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