using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; namespace Zhaizj.Framework { /// /// 常用 hash 算法类型 /// public enum HashType { MD5, MD5_16, SHA1, SHA256, SHA384, SHA512 } /// /// 封装了常用 hash 算法 /// public class HashTool : IHashTool { /// /// 根据指定的 hash 算法,加密字符串(比如密码) /// /// 需要 hash 的字符串 /// hash 算法类型 /// public virtual String Get( String pwd, HashType ht ) { HashAlgorithm algorithm; if (ht == HashType.MD5 || ht == HashType.MD5_16) algorithm = MD5.Create(); else if (ht == HashType.SHA1) algorithm = SHA1CryptoServiceProvider.Create(); else if (ht == HashType.SHA256) algorithm = SHA256Managed.Create(); else if (ht == HashType.SHA384) algorithm = SHA384Managed.Create(); else if (ht == HashType.SHA512) algorithm = SHA512Managed.Create(); else algorithm = MD5.Create(); byte[] buffer = Encoding.UTF8.GetBytes( pwd ); String result = BitConverter.ToString( algorithm.ComputeHash( buffer ) ).Replace( "-", "" ); if (ht == HashType.MD5_16) return result.Substring( 8, 16 ).ToLower(); return result; } /// /// 根据 hash 算法和指定的 salt,加密字符串 /// /// /// 指定的 salt /// hash 算法类型 /// public virtual String GetBySalt( String pwd, String salt, HashType ht ) { return Get( pwd + salt, ht ); } /// /// 获取随机密码(由英文字母和数字构成) /// /// 密码长度 /// public virtual String GetRandomPassword( int passwordLength ) { return GetRandomPassword( passwordLength, true ); } /// /// 获取随机密码(由英文字母和数字构成) /// /// 密码长度 /// 结果是否小写 /// public virtual String GetRandomPassword( int passwordLength, Boolean isLower ) { String charList = isLower ? "abcdefghijklmnopqrstuvwxyz0123456789" : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; byte[] buffer = new byte[passwordLength]; RNGCryptoServiceProvider.Create().GetBytes( buffer ); char[] chars = new char[passwordLength]; int charCount = charList.Length; for (int i = 0; i < passwordLength; i++) { chars[i] = charList[(int)buffer[i] % charCount]; } return new string( chars ); } /// /// 根据指定长度获取salt /// /// salt的长度 /// public virtual String GetSalt( int size ) { byte[] buffer = new byte[size]; RNGCryptoServiceProvider.Create().GetBytes( buffer ); return BitConverter.ToString( buffer ).Replace( "-", "" ); } } }