HashProvider

using System;
using System.Text;
using System.Security.Cryptography;

namespace Business.Manager
{
 /// <summary>
 /// HashProvider 的摘要说明。
 /// </summary>
 public sealed class HashProvider
 {
  public const int saltLength = 8;
  /// <summary>
  /// 创建一个Hash
  /// </summary>
  /// <param name="plainText"></param>
  /// <returns></returns>
  public byte[] CreateHash(string plainText)
  {
   byte[] hash = CreateTextHash(plainText);
   byte[] saltValue = new byte[saltLength];
   RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
   rng.GetBytes(saltValue);
   return CreateSaltedTextHash(hash, saltValue);
  }
  private byte[] CreateTextHash(string plainText)
  {
   UTF8Encoding enc = new UTF8Encoding();
   SHA1 sha1 = SHA1.Create();
   return sha1.ComputeHash(enc.GetBytes(plainText));
  }
  private byte[] CreateSaltedTextHash(byte[] hash, byte[] saltValue)
  {
   byte[] rawHash = new byte[hash.Length + saltValue.Length];
   hash.CopyTo(rawHash, 0);
   saltValue.CopyTo(rawHash, hash.Length);
   SHA1 sha1 = SHA1.Create();
   byte[] saltedHash = sha1.ComputeHash(rawHash);
   byte[] finallyHash = new byte[saltedHash.Length + saltValue.Length];
   saltedHash.CopyTo(finallyHash, 0);
   saltValue.CopyTo(finallyHash, saltedHash.Length);

   return finallyHash;
  }
  /// <summary>
  /// 比较Hash
  /// </summary>
  /// <param name="plaintext"></param>
  /// <param name="hashedText"></param>
  /// <returns></returns>
  public bool CompareHash(string plainText, byte[] hashedText)
  {
   if ( plainText == null || hashedText == null )
   {
    return false;
   }
   byte[] hash = CreateTextHash(plainText);
   if ( hash.Length != hashedText.Length - saltLength )
   {
    return false;
   }
   byte[] saltValue = new byte[saltLength];
   int saltOffset = hashedText.Length - saltLength;
   for ( int i = 0; i < saltLength; i++ )
   {
    saltValue[i] = hashedText[saltOffset + i];
   }
   byte[] saltedHash = CreateSaltedTextHash(hash, saltValue);

   return CompareBytes(hashedText, saltedHash);
  }
  private bool CompareBytes(byte[] array1, byte[] array2)
  {
   if ( array1.Length != array2.Length )
   {
    return false;
   }
   for ( int i = 0; i < array1.Length; i++ )
   {
    if ( array1[i] != array2[i] )
    {
     return false;
    }
   }
   return true;
  }
 }
}

posted on 2005-09-18 23:30  刘余学  阅读(111)  评论(0)    收藏  举报

导航