PasswordHash.cs 7.0 KB

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