PasswordHash.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace MediaBrowser.Model.Cryptography
  5. {
  6. public class PasswordHash
  7. {
  8. //Defined from this hash storage spec
  9. //https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
  10. //$<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
  11. public string Id;
  12. public Dictionary<string, string> Parameters = new Dictionary<string, string>();
  13. public string Salt;
  14. public byte[] SaltBytes;
  15. public string Hash;
  16. public byte[] HashBytes;
  17. public PasswordHash(string StorageString)
  18. {
  19. string[] a = StorageString.Split('$');
  20. Id = a[1];
  21. if (a[2].Contains("="))
  22. {
  23. foreach (string paramset in (a[2].Split(',')))
  24. {
  25. if (!String.IsNullOrEmpty(paramset))
  26. {
  27. string[] fields = paramset.Split('=');
  28. Parameters.Add(fields[0], fields[1]);
  29. }
  30. }
  31. if (a.Length == 4)
  32. {
  33. Salt = a[2];
  34. SaltBytes = Convert.FromBase64CharArray(Salt.ToCharArray(), 0, Salt.Length);
  35. Hash = a[3];
  36. HashBytes = Convert.FromBase64CharArray(Hash.ToCharArray(), 0, Hash.Length);
  37. }
  38. else
  39. {
  40. Salt = string.Empty;
  41. Hash = a[3];
  42. HashBytes = Convert.FromBase64CharArray(Hash.ToCharArray(), 0, Hash.Length);
  43. }
  44. }
  45. else
  46. {
  47. if (a.Length == 4)
  48. {
  49. Salt = a[2];
  50. SaltBytes = Convert.FromBase64CharArray(Salt.ToCharArray(), 0, Salt.Length);
  51. Hash = a[3];
  52. HashBytes = Convert.FromBase64CharArray(Hash.ToCharArray(), 0, Hash.Length);
  53. }
  54. else
  55. {
  56. Salt = string.Empty;
  57. Hash = a[2];
  58. HashBytes = Convert.FromBase64CharArray(Hash.ToCharArray(), 0, Hash.Length);
  59. }
  60. }
  61. }
  62. public PasswordHash(ICryptoProvider cryptoProvider2)
  63. {
  64. Id = "SHA256";
  65. SaltBytes = cryptoProvider2.GenerateSalt();
  66. Salt = Convert.ToBase64String(SaltBytes);
  67. }
  68. private string SerializeParameters()
  69. {
  70. string ReturnString = String.Empty;
  71. foreach (var KVP in Parameters)
  72. {
  73. ReturnString += String.Format(",{0}={1}", KVP.Key, KVP.Value);
  74. }
  75. if (ReturnString[0] == ',')
  76. {
  77. ReturnString = ReturnString.Remove(0, 1);
  78. }
  79. return ReturnString;
  80. }
  81. public override string ToString()
  82. {
  83. return String.Format("${0}${1}${2}${3}", Id, SerializeParameters(), Salt, Hash);
  84. }
  85. }
  86. }