Comparing SecureStrings

After writing about SecureStrings, you soon come to realise that holding the secret information you are going to have to make some comparisons at some point. For example, if you need to check a password.

The important thing to remember is not to expose the password as text or hold it in memory for anyone or anything to sniff it out.

This code snippet does the job, but it what it does expose is a Timing Attack, but we will deal with that issue another day.

public static bool IsEqualTo(this SecureString ss1, SecureString ss2)
 if (ss1 == null)
 throw new ArgumentNullException("s1");

if (ss2 == null)
 throw new ArgumentNullException("s2");

if (ss1.Length != ss2.Length)
 return false;

IntPtr bstr1 = IntPtr.Zero;
 IntPtr bstr2 = IntPtr.Zero;
 bstr1 = Marshal.SecureStringToBSTR(ss1);
 bstr2 = Marshal.SecureStringToBSTR(ss2);

int length1 = Marshal.ReadInt32(bstr1, -4);

for (int x = 0; x < length1; ++x)
 byte b1 = Marshal.ReadByte(bstr1, x);
 byte b2 = Marshal.ReadByte(bstr2, x);
 if (b1 != b2) return false;
 return true;
 if (bstr2 != IntPtr.Zero) Marshal.ZeroFreeBSTR(bstr2);
 if (bstr1 != IntPtr.Zero) Marshal.ZeroFreeBSTR(bstr1);