SecureString is useful when dealing with passwords, but its usage can seem complicated compared to regular strings. You have to add characters one by one, comparisons with plain strings are cumbersome, and there are many other friction points that can discourage developers. The ToSecureString and ToUnsecureString extension methods make it easier to work with:
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 significantly faster (about 10-15x) than adding characters one by one.
Do you have a question or a suggestion about this post? Contact me!