I see Microsoft provide a SecureString: https://msdn.microsoft.com/en-us/library/system.security.securestring(v=vs.110).aspx, is it possible to compare two SecureStrings and ensure it is safe against Timing Attacks?
I wrote a blog post about this. I came up with two solutions:
- Using either Marshal.ReadByte or unsafe pointer code you can loop over the SecureString, just as in this answer. However, don't bail early if one of the characters is different; this is not time-safe. Instead, XOR all characters and return the result. If all characters are equal, all XORs will return 0.
- Use P/Invoke and the Windows Crypto API to create a hash of the two strings, and compare those normally. Bonus points for using a random secret key to create the hash, so that the attacker can't know the hash that it being compared.
Note that this is all very advanced and protects against unlikely threats while introducing a lot of complexity. For most cases I would avoid SecureStrings.