Posted By

gujingshui on 08/11/14


Tagged

security hash Solt


Versions (?)

创建Solted hash


 / Published in: C#
 

来自StockTrader Dbloader

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6.  
  7. namespace Loader
  8. {
  9.  
  10. public sealed class SaltedHash
  11. {
  12. public string Salt { get { return _salt; } }
  13. public string Hash { get { return _hash; } }
  14.  
  15. public static SaltedHash Create(string password)
  16. {
  17. string salt = _createSalt();
  18. string hash = _calculateHash(salt, password);
  19. return new SaltedHash(salt, hash);
  20. }
  21.  
  22. public static SaltedHash Create(string salt, string hash)
  23. {
  24. return new SaltedHash(salt, hash);
  25. }
  26.  
  27. public bool Verify(string password)
  28. {
  29. string h = _calculateHash(_salt, password);
  30. return _hash.Equals(h);
  31. }
  32.  
  33. private SaltedHash(string s, string h)
  34. {
  35. _salt = s;
  36. _hash = h;
  37. }
  38.  
  39. private static string _createSalt()
  40. {
  41. byte[] r = _createRandomBytes(saltLength);
  42. return Convert.ToBase64String(r);
  43. }
  44.  
  45. private static byte[] _createRandomBytes(int len)
  46. {
  47. byte[] r = new byte[len];
  48. new RNGCryptoServiceProvider().GetBytes(r);
  49. return r;
  50. }
  51.  
  52. private static string _calculateHash(string salt, string password)
  53. {
  54. byte[] data = _toByteArray(salt + password);
  55. byte[] hash = _calculateHash(data);
  56. return Convert.ToBase64String(hash);
  57. }
  58.  
  59. private static byte[] _calculateHash(byte[] data)
  60. {
  61. return new SHA1CryptoServiceProvider().ComputeHash(data);
  62. }
  63.  
  64. private static byte[] _toByteArray(string s)
  65. {
  66. return System.Text.Encoding.UTF8.GetBytes(s);
  67. }
  68.  
  69. private readonly string _salt;
  70. private readonly string _hash;
  71. private const int saltLength = 12;
  72. }
  73.  
  74. }

Report this snippet  

You need to login to post a comment.