PasswordHash.cs 7.1 KB

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