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 perseverants. Using both
ToUnsecureString extensions makes it easier to use:
public static string ToUnsecureString(this SecureString secureString)
Contract.Requires(secureString != null);
Contract.Ensures(Contract.Result<string>() != null);
IntPtr unmanagedString = IntPtr.Zero;
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
public static SecureString ToSecureString(this string s)
Contract.Requires(s != null);
Contract.Ensures(Contract.Result<SecureString>() != null);
fixed (char* passwordChars = s)
var securePassword = new SecureString(passwordChars, s.Length);
Note the use of the unsafe constuctor 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!