The Labs \ Source Viewer \ SSCLI \ System.Xml \ SecureStringHasher

  1. //------------------------------------------------------------------------------
  2. // <copyright file="SecureStringHasher.cs" company="Microsoft">
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. // </copyright>
  14. //------------------------------------------------------------------------------
  15. using System;
  16. using System.Collections.Generic;
  17. namespace System.Xml
  18. {
  19.    
  20.     // SecureStringHasher is a hash code provider for strings. The hash codes calculation starts with a seed (hasCodeRandomizer) which is usually
  21.     // different for each instance of SecureStringHasher. Since the hash code depend on the seed, the chance of hashtable DoS attack in case when
  22.     // someone passes in lots of strings that hash to the same hash code is greatly reduced.
  23.     // The SecureStringHasher implements IEqualityComparer for strings and therefore can be used in generic IDictionary.
  24.     internal class SecureStringHasher : IEqualityComparer<string>
  25.     {
  26.         int hashCodeRandomizer;
  27.        
  28.         public SecureStringHasher()
  29.         {
  30.             this.hashCodeRandomizer = Environment.TickCount;
  31.         }
  32.        
  33.         public SecureStringHasher(int hashCodeRandomizer)
  34.         {
  35.             this.hashCodeRandomizer = hashCodeRandomizer;
  36.         }
  37.        
  38.        
  39.         public int Compare(string x, string y)
  40.         {
  41.             return String.Compare(x, y, StringComparison.Ordinal);
  42.         }
  43.        
  44.         public bool Equals(string x, string y)
  45.         {
  46.             return String.Equals(x, y, StringComparison.Ordinal);
  47.         }
  48.        
  49.         public int GetHashCode(string key)
  50.         {
  51.             int hashCode = hashCodeRandomizer;
  52.             // use key.Length to eliminate the rangecheck
  53.             for (int i = 0; i < key.Length; i++) {
  54.                 hashCode += (hashCode << 7) ^ key[i];
  55.             }
  56.             // mix it a bit more
  57.             hashCode -= hashCode >> 17;
  58.             hashCode -= hashCode >> 11;
  59.             hashCode -= hashCode >> 5;
  60.             return hashCode;
  61.         }
  62.     }
  63. }

Developer Fusion