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?


1 Answer 1


I wrote a blog post about this. I came up with two solutions:

  1. 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.
  2. 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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .