PasswordHash.cs 7.1 KB

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