PasswordHash.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. namespace MediaBrowser.Model.Cryptography
  6. {
  7. // Defined from this hash storage spec
  8. // https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
  9. // $<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
  10. // with one slight amendment to ease the transition, we're writing out the bytes in hex
  11. // rather than making them a BASE64 string with stripped padding
  12. public class PasswordHash
  13. {
  14. private readonly Dictionary<string, string> _parameters;
  15. private readonly byte[] _salt;
  16. private readonly byte[] _hash;
  17. public PasswordHash(string id, byte[] hash)
  18. : this(id, hash, Array.Empty<byte>())
  19. {
  20. }
  21. public PasswordHash(string id, byte[] hash, byte[] salt)
  22. : this(id, hash, salt, new Dictionary<string, string>())
  23. {
  24. }
  25. public PasswordHash(string id, byte[] hash, byte[] salt, Dictionary<string, string> parameters)
  26. {
  27. ArgumentException.ThrowIfNullOrEmpty(id);
  28. Id = id;
  29. _hash = hash;
  30. _salt = salt;
  31. _parameters = parameters;
  32. }
  33. /// <summary>
  34. /// Gets the symbolic name for the function used.
  35. /// </summary>
  36. /// <value>Returns the symbolic name for the function used.</value>
  37. public string Id { get; }
  38. /// <summary>
  39. /// Gets the additional parameters used by the hash function.
  40. /// </summary>
  41. public IReadOnlyDictionary<string, string> Parameters => _parameters;
  42. /// <summary>
  43. /// Gets the salt used for hashing the password.
  44. /// </summary>
  45. /// <value>Returns the salt used for hashing the password.</value>
  46. public ReadOnlySpan<byte> Salt => _salt;
  47. /// <summary>
  48. /// Gets the hashed password.
  49. /// </summary>
  50. /// <value>Return the hashed password.</value>
  51. public ReadOnlySpan<byte> Hash => _hash;
  52. public static PasswordHash Parse(ReadOnlySpan<char> hashString)
  53. {
  54. if (hashString.IsEmpty)
  55. {
  56. throw new ArgumentException("String can't be empty", nameof(hashString));
  57. }
  58. if (hashString[0] != '$')
  59. {
  60. throw new FormatException("Hash string must start with a $");
  61. }
  62. // Ignore first $
  63. hashString = hashString[1..];
  64. int nextSegment = hashString.IndexOf('$');
  65. if (hashString.IsEmpty || nextSegment == 0)
  66. {
  67. throw new FormatException("Hash string must contain a valid id");
  68. }
  69. else if (nextSegment == -1)
  70. {
  71. return new PasswordHash(hashString.ToString(), Array.Empty<byte>());
  72. }
  73. ReadOnlySpan<char> id = hashString[..nextSegment];
  74. hashString = hashString[(nextSegment + 1)..];
  75. Dictionary<string, string>? parameters = null;
  76. nextSegment = hashString.IndexOf('$');
  77. // Optional parameters
  78. ReadOnlySpan<char> parametersSpan = nextSegment == -1 ? hashString : hashString[..nextSegment];
  79. if (parametersSpan.Contains('='))
  80. {
  81. while (!parametersSpan.IsEmpty)
  82. {
  83. ReadOnlySpan<char> parameter;
  84. int index = parametersSpan.IndexOf(',');
  85. if (index == -1)
  86. {
  87. parameter = parametersSpan;
  88. parametersSpan = ReadOnlySpan<char>.Empty;
  89. }
  90. else
  91. {
  92. parameter = parametersSpan[..index];
  93. parametersSpan = parametersSpan[(index + 1)..];
  94. }
  95. int splitIndex = parameter.IndexOf('=');
  96. if (splitIndex == -1 || splitIndex == 0 || splitIndex == parameter.Length - 1)
  97. {
  98. throw new FormatException("Malformed parameter in password hash string");
  99. }
  100. (parameters ??= new Dictionary<string, string>()).Add(
  101. parameter[..splitIndex].ToString(),
  102. parameter[(splitIndex + 1)..].ToString());
  103. }
  104. if (nextSegment == -1)
  105. {
  106. // parameters can't be null here
  107. return new PasswordHash(id.ToString(), Array.Empty<byte>(), Array.Empty<byte>(), parameters!);
  108. }
  109. hashString = hashString[(nextSegment + 1)..];
  110. nextSegment = hashString.IndexOf('$');
  111. }
  112. if (nextSegment == 0)
  113. {
  114. throw new FormatException("Hash string contains an empty segment");
  115. }
  116. byte[] hash;
  117. byte[] salt;
  118. if (nextSegment == -1)
  119. {
  120. salt = Array.Empty<byte>();
  121. hash = Convert.FromHexString(hashString);
  122. }
  123. else
  124. {
  125. salt = Convert.FromHexString(hashString[..nextSegment]);
  126. hashString = hashString[(nextSegment + 1)..];
  127. nextSegment = hashString.IndexOf('$');
  128. if (nextSegment != -1)
  129. {
  130. throw new FormatException("Hash string contains too many segments");
  131. }
  132. if (hashString.IsEmpty)
  133. {
  134. throw new FormatException("Hash segment is empty");
  135. }
  136. hash = Convert.FromHexString(hashString);
  137. }
  138. return new PasswordHash(id.ToString(), hash, salt, parameters ?? new Dictionary<string, string>());
  139. }
  140. private void SerializeParameters(StringBuilder stringBuilder)
  141. {
  142. if (_parameters.Count == 0)
  143. {
  144. return;
  145. }
  146. stringBuilder.Append('$');
  147. foreach (var pair in _parameters)
  148. {
  149. stringBuilder.Append(pair.Key)
  150. .Append('=')
  151. .Append(pair.Value)
  152. .Append(',');
  153. }
  154. // Remove last ','
  155. stringBuilder.Length -= 1;
  156. }
  157. /// <inheritdoc />
  158. public override string ToString()
  159. {
  160. var str = new StringBuilder()
  161. .Append('$')
  162. .Append(Id);
  163. SerializeParameters(str);
  164. if (_salt.Length != 0)
  165. {
  166. str.Append('$')
  167. .Append(Convert.ToHexString(_salt));
  168. }
  169. if (_hash.Length != 0)
  170. {
  171. str.Append('$')
  172. .Append(Convert.ToHexString(_hash));
  173. }
  174. return str.ToString();
  175. }
  176. }
  177. }