What is best way to create SecureString(unicode encoded) from byte array?
I want to store my decrypted DEK key in memory, the decryption process is made by Azure.KeyVault(api), that produce byte array as a result.
var keyBytes = client.DecryptAsync(url, keyName, keyVersion, algorithm, encryptedKeyBytes).GetAwaiter().GetResult().Result;
I have created something like that but I am not proud from that implementations.
var secureKey = new SecureString();
var secureKeyCharArray = Encoding.Unicode.GetChars(keyBytes);
for (int i = 0; i < keyBytes.Length; i++)
{
keyBytes[i] = 0;
}
for (int i = 0; i < secureKeyCharArray.Length; i++)
{
secureKey.AppendChar(secureKeyCharArray[i]);
secureKeyCharArray[i] = (char)0;
}
secureKey.MakeReadOnly();
After rewriting DEK key to SecureString variable I am cleaning both array: secureKeyCharArray and keyBytes but i dont know that it is enough.
Do you know some better solutions for that case? Maybe some nuget packages? Or maybe my whole idea is wrong?
Thanks for any suggestion.
=== Edited ===============================================================
But if we focus on storing secure data in memeory, do you know any better solution than SecureString? Work with this type is a little bit dificult, for example to read key from that vartiable I am using something like that:
IntPtr unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
return Marshal.PtrToStringUni(unmanagedString);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
}
I dont know that it is ok for production purpose to use Marshal classes.
unsafecode to wipe the contents when they're doneSecureStringthat it is virtually unusable by anything :) what I am saying is that you need to be really careful about the lifetime when you do access the content, and just returning a string doesn't make that obvious to the consumer