4

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?

Coppermill
  • 141
  • 3
  • 1
    See also [compare two SecureStrings for equality](https://stackoverflow.com/questions/4502676/c-sharp-compare-two-securestrings-for-equality) – Sjoerd Jun 06 '17 at 17:15
  • The link you have provided does indeed compare two SecureStrings, but it is not safe against Timing Attacks – Coppermill Jun 08 '17 at 07:31

1 Answers1

2

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.

Sjoerd
  • 28,707
  • 12
  • 74
  • 102