PasswordHash.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. ArgumentNullException.ThrowIfNull(id);
  28. if (id.Length == 0)
  29. {
  30. throw new ArgumentException("String can't be empty", nameof(id));
  31. }
  32. Id = id;
  33. _hash = hash;
  34. _salt = salt;
  35. _parameters = parameters;
  36. }
  37. /// <summary>
  38. /// Gets the symbolic name for the function used.
  39. /// </summary>
  40. /// <value>Returns the symbolic name for the function used.</value>
  41. public string Id { get; }
  42. /// <summary>
  43. /// Gets the additional parameters used by the hash function.
  44. /// </summary>
  45. public IReadOnlyDictionary<string, string> Parameters => _parameters;
  46. /// <summary>
  47. /// Gets the salt used for hashing the password.
  48. /// </summary>
  49. /// <value>Returns the salt used for hashing the password.</value>
  50. public ReadOnlySpan<byte> Salt => _salt;
  51. /// <summary>
  52. /// Gets the hashed password.
  53. /// </summary>
  54. /// <value>Return the hashed password.</value>
  55. public ReadOnlySpan<byte> Hash => _hash;
  56. public static PasswordHash Parse(ReadOnlySpan<char> hashString)
  57. {
  58. if (hashString.IsEmpty)
  59. {
  60. throw new ArgumentException("String can't be empty", nameof(hashString));
  61. }
  62. if (hashString[0] != '$')
  63. {
  64. throw new FormatException("Hash string must start with a $");
  65. }
  66. // Ignore first $
  67. hashString = hashString[1..];
  68. int nextSegment = hashString.IndexOf('$');
  69. if (hashString.IsEmpty || nextSegment == 0)
  70. {
  71. throw new FormatException("Hash string must contain a valid id");
  72. }
  73. else if (nextSegment == -1)
  74. {
  75. return new PasswordHash(hashString.ToString(), Array.Empty<byte>());
  76. }
  77. ReadOnlySpan<char> id = hashString[..nextSegment];
  78. hashString = hashString[(nextSegment + 1)..];
  79. Dictionary<string, string>? parameters = null;
  80. nextSegment = hashString.IndexOf('$');
  81. // Optional parameters
  82. ReadOnlySpan<char> parametersSpan = nextSegment == -1 ? hashString : hashString[..nextSegment];
  83. if (parametersSpan.Contains('='))
  84. {
  85. while (!parametersSpan.IsEmpty)
  86. {
  87. ReadOnlySpan<char> parameter;
  88. int index = parametersSpan.IndexOf(',');
  89. if (index == -1)
  90. {
  91. parameter = parametersSpan;
  92. parametersSpan = ReadOnlySpan<char>.Empty;
  93. }
  94. else
  95. {
  96. parameter = parametersSpan[..index];
  97. parametersSpan = parametersSpan[(index + 1)..];
  98. }
  99. int splitIndex = parameter.IndexOf('=');
  100. if (splitIndex == -1 || splitIndex == 0 || splitIndex == parameter.Length - 1)
  101. {
  102. throw new FormatException("Malformed parameter in password hash string");
  103. }
  104. (parameters ??= new Dictionary<string, string>()).Add(
  105. parameter[..splitIndex].ToString(),
  106. parameter[(splitIndex + 1)..].ToString());
  107. }
  108. if (nextSegment == -1)
  109. {
  110. // parameters can't be null here
  111. return new PasswordHash(id.ToString(), Array.Empty<byte>(), Array.Empty<byte>(), parameters!);
  112. }
  113. hashString = hashString[(nextSegment + 1)..];
  114. nextSegment = hashString.IndexOf('$');
  115. }
  116. if (nextSegment == 0)
  117. {
  118. throw new FormatException("Hash string contains an empty segment");
  119. }
  120. byte[] hash;
  121. byte[] salt;
  122. if (nextSegment == -1)
  123. {
  124. salt = Array.Empty<byte>();
  125. hash = Convert.FromHexString(hashString);
  126. }
  127. else
  128. {
  129. salt = Convert.FromHexString(hashString[..nextSegment]);
  130. hashString = hashString[(nextSegment + 1)..];
  131. nextSegment = hashString.IndexOf('$');
  132. if (nextSegment != -1)
  133. {
  134. throw new FormatException("Hash string contains too many segments");
  135. }
  136. if (hashString.IsEmpty)
  137. {
  138. throw new FormatException("Hash segment is empty");
  139. }
  140. hash = Convert.FromHexString(hashString);
  141. }
  142. return new PasswordHash(id.ToString(), hash, salt, parameters ?? new Dictionary<string, string>());
  143. }
  144. private void SerializeParameters(StringBuilder stringBuilder)
  145. {
  146. if (_parameters.Count == 0)
  147. {
  148. return;
  149. }
  150. stringBuilder.Append('$');
  151. foreach (var pair in _parameters)
  152. {
  153. stringBuilder.Append(pair.Key)
  154. .Append('=')
  155. .Append(pair.Value)
  156. .Append(',');
  157. }
  158. // Remove last ','
  159. stringBuilder.Length -= 1;
  160. }
  161. /// <inheritdoc />
  162. public override string ToString()
  163. {
  164. var str = new StringBuilder()
  165. .Append('$')
  166. .Append(Id);
  167. SerializeParameters(str);
  168. if (_salt.Length != 0)
  169. {
  170. str.Append('$')
  171. .Append(Convert.ToHexString(_salt));
  172. }
  173. if (_hash.Length != 0)
  174. {
  175. str.Append('$')
  176. .Append(Convert.ToHexString(_hash));
  177. }
  178. return str.ToString();
  179. }
  180. }
  181. }