Using SecureString
The SecureString
are useful when dealing with passwords, however their use may seem complicated compared to the classic strings. Indeed you have to add the characters one by one, comparisons with a string of characters are complicated… In short, many things that can discourage the less perseverant. Using both ToSecureString
and ToUnsecureString
extensions makes it easier to use:
C#
public static string ToUnsecureString(this SecureString secureString)
{
Contract.Requires(secureString != null);
Contract.Ensures(Contract.Result<string>() != null);
IntPtr unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
return Marshal.PtrToStringUni(unmanagedString);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
}
}
public static SecureString ToSecureString(this string s)
{
Contract.Requires(s != null);
Contract.Ensures(Contract.Result<SecureString>() != null);
unsafe
{
fixed (char* passwordChars = s)
{
var securePassword = new SecureString(passwordChars, s.Length);
securePassword.MakeReadOnly();
return securePassword;
}
}
}
Note the use of the unsafe constructor of SecureString
. This is much more performant (about 10-15x) than adding characters one by one.
Do you have a question or a suggestion about this post? Contact me!
Enjoy this blog?💖 Sponsor on GitHub