DataProtectionCommonExtensions.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using Microsoft.AspNetCore.DataProtection.Abstractions;
  7. using Microsoft.Extensions.Internal;
  8. namespace Microsoft.AspNetCore.DataProtection
  9. {
  10. /// <summary>
  11. /// Helpful extension methods for data protection APIs.
  12. /// </summary>
  13. public static class DataProtectionCommonExtensions
  14. {
  15. /// <summary>
  16. /// Creates an <see cref="IDataProtector"/> given a list of purposes.
  17. /// </summary>
  18. /// <param name="provider">The <see cref="IDataProtectionProvider"/> from which to generate the purpose chain.</param>
  19. /// <param name="purposes">The list of purposes which contribute to the purpose chain. This list must
  20. /// contain at least one element, and it may not contain null elements.</param>
  21. /// <returns>An <see cref="IDataProtector"/> tied to the provided purpose chain.</returns>
  22. /// <remarks>
  23. /// This is a convenience method which chains together several calls to
  24. /// <see cref="IDataProtectionProvider.CreateProtector(string)"/>. See that method's
  25. /// documentation for more information.
  26. /// </remarks>
  27. public static IDataProtector CreateProtector(this IDataProtectionProvider provider, IEnumerable<string> purposes)
  28. {
  29. if (provider == null)
  30. {
  31. throw new ArgumentNullException(nameof(provider));
  32. }
  33. if (purposes == null)
  34. {
  35. throw new ArgumentNullException(nameof(purposes));
  36. }
  37. bool collectionIsEmpty = true;
  38. IDataProtectionProvider retVal = provider;
  39. foreach (string purpose in purposes)
  40. {
  41. if (purpose == null)
  42. {
  43. throw new ArgumentException(Resources.DataProtectionExtensions_NullPurposesCollection, nameof(purposes));
  44. }
  45. retVal = retVal.CreateProtector(purpose) ?? CryptoUtil.Fail<IDataProtector>("CreateProtector returned null.");
  46. collectionIsEmpty = false;
  47. }
  48. if (collectionIsEmpty)
  49. {
  50. throw new ArgumentException(Resources.DataProtectionExtensions_NullPurposesCollection, nameof(purposes));
  51. }
  52. Debug.Assert(retVal is IDataProtector); // CreateProtector is supposed to return an instance of this interface
  53. return (IDataProtector)retVal;
  54. }
  55. /// <summary>
  56. /// Creates an <see cref="IDataProtector"/> given a list of purposes.
  57. /// </summary>
  58. /// <param name="provider">The <see cref="IDataProtectionProvider"/> from which to generate the purpose chain.</param>
  59. /// <param name="purpose">The primary purpose used to create the <see cref="IDataProtector"/>.</param>
  60. /// <param name="subPurposes">An optional list of secondary purposes which contribute to the purpose chain.
  61. /// If this list is provided it cannot contain null elements.</param>
  62. /// <returns>An <see cref="IDataProtector"/> tied to the provided purpose chain.</returns>
  63. /// <remarks>
  64. /// This is a convenience method which chains together several calls to
  65. /// <see cref="IDataProtectionProvider.CreateProtector(string)"/>. See that method's
  66. /// documentation for more information.
  67. /// </remarks>
  68. public static IDataProtector CreateProtector(this IDataProtectionProvider provider, string purpose, params string[] subPurposes)
  69. {
  70. if (provider == null)
  71. {
  72. throw new ArgumentNullException(nameof(provider));
  73. }
  74. if (purpose == null)
  75. {
  76. throw new ArgumentNullException(nameof(purpose));
  77. }
  78. // The method signature isn't simply CreateProtector(this IDataProtectionProvider, params string[] purposes)
  79. // because we don't want the code provider.CreateProtector() [parameterless] to inadvertently compile.
  80. // The actual signature for this method forces at least one purpose to be provided at the call site.
  81. IDataProtector protector = provider.CreateProtector(purpose);
  82. if (subPurposes != null && subPurposes.Length > 0)
  83. {
  84. protector = protector?.CreateProtector((IEnumerable<string>)subPurposes);
  85. }
  86. return protector ?? CryptoUtil.Fail<IDataProtector>("CreateProtector returned null.");
  87. }
  88. /// <summary>
  89. /// Retrieves an <see cref="IDataProtectionProvider"/> from an <see cref="IServiceProvider"/>.
  90. /// </summary>
  91. /// <param name="services">The service provider from which to retrieve the <see cref="IDataProtectionProvider"/>.</param>
  92. /// <returns>An <see cref="IDataProtectionProvider"/>. This method is guaranteed never to return null.</returns>
  93. /// <exception cref="InvalidOperationException">If no <see cref="IDataProtectionProvider"/> service exists in <paramref name="services"/>.</exception>
  94. public static IDataProtectionProvider GetDataProtectionProvider(this IServiceProvider services)
  95. {
  96. if (services == null)
  97. {
  98. throw new ArgumentNullException(nameof(services));
  99. }
  100. // We have our own implementation of GetRequiredService<T> since we don't want to
  101. // take a dependency on DependencyInjection.Interfaces.
  102. IDataProtectionProvider provider = (IDataProtectionProvider)services.GetService(typeof(IDataProtectionProvider));
  103. if (provider == null)
  104. {
  105. throw new InvalidOperationException(Resources.FormatDataProtectionExtensions_NoService(typeof(IDataProtectionProvider).FullName));
  106. }
  107. return provider;
  108. }
  109. /// <summary>
  110. /// Retrieves an <see cref="IDataProtector"/> from an <see cref="IServiceProvider"/> given a list of purposes.
  111. /// </summary>
  112. /// <param name="services">An <see cref="IServiceProvider"/> which contains the <see cref="IDataProtectionProvider"/>
  113. /// from which to generate the purpose chain.</param>
  114. /// <param name="purposes">The list of purposes which contribute to the purpose chain. This list must
  115. /// contain at least one element, and it may not contain null elements.</param>
  116. /// <returns>An <see cref="IDataProtector"/> tied to the provided purpose chain.</returns>
  117. /// <remarks>
  118. /// This is a convenience method which calls <see cref="GetDataProtectionProvider(IServiceProvider)"/>
  119. /// then <see cref="CreateProtector(IDataProtectionProvider, IEnumerable{string})"/>. See those methods'
  120. /// documentation for more information.
  121. /// </remarks>
  122. public static IDataProtector GetDataProtector(this IServiceProvider services, IEnumerable<string> purposes)
  123. {
  124. if (services == null)
  125. {
  126. throw new ArgumentNullException(nameof(services));
  127. }
  128. if (purposes == null)
  129. {
  130. throw new ArgumentNullException(nameof(purposes));
  131. }
  132. return services.GetDataProtectionProvider().CreateProtector(purposes);
  133. }
  134. /// <summary>
  135. /// Retrieves an <see cref="IDataProtector"/> from an <see cref="IServiceProvider"/> given a list of purposes.
  136. /// </summary>
  137. /// <param name="services">An <see cref="IServiceProvider"/> which contains the <see cref="IDataProtectionProvider"/>
  138. /// from which to generate the purpose chain.</param>
  139. /// <param name="purpose">The primary purpose used to create the <see cref="IDataProtector"/>.</param>
  140. /// <param name="subPurposes">An optional list of secondary purposes which contribute to the purpose chain.
  141. /// If this list is provided it cannot contain null elements.</param>
  142. /// <returns>An <see cref="IDataProtector"/> tied to the provided purpose chain.</returns>
  143. /// <remarks>
  144. /// This is a convenience method which calls <see cref="GetDataProtectionProvider(IServiceProvider)"/>
  145. /// then <see cref="CreateProtector(IDataProtectionProvider, string, string[])"/>. See those methods'
  146. /// documentation for more information.
  147. /// </remarks>
  148. public static IDataProtector GetDataProtector(this IServiceProvider services, string purpose, params string[] subPurposes)
  149. {
  150. if (services == null)
  151. {
  152. throw new ArgumentNullException(nameof(services));
  153. }
  154. if (purpose == null)
  155. {
  156. throw new ArgumentNullException(nameof(purpose));
  157. }
  158. return services.GetDataProtectionProvider().CreateProtector(purpose, subPurposes);
  159. }
  160. /// <summary>
  161. /// Cryptographically protects a piece of plaintext data.
  162. /// </summary>
  163. /// <param name="protector">The data protector to use for this operation.</param>
  164. /// <param name="plaintext">The plaintext data to protect.</param>
  165. /// <returns>The protected form of the plaintext data.</returns>
  166. public static string Protect(this IDataProtector protector, string plaintext)
  167. {
  168. if (protector == null)
  169. {
  170. throw new ArgumentNullException(nameof(protector));
  171. }
  172. if (plaintext == null)
  173. {
  174. throw new ArgumentNullException(nameof(plaintext));
  175. }
  176. try
  177. {
  178. byte[] plaintextAsBytes = EncodingUtil.SecureUtf8Encoding.GetBytes(plaintext);
  179. byte[] protectedDataAsBytes = protector.Protect(plaintextAsBytes);
  180. return WebEncoders.Base64UrlEncode(protectedDataAsBytes);
  181. }
  182. catch (Exception ex) when (ex.RequiresHomogenization())
  183. {
  184. // Homogenize exceptions to CryptographicException
  185. throw Error.CryptCommon_GenericError(ex);
  186. }
  187. }
  188. /// <summary>
  189. /// Cryptographically unprotects a piece of protected data.
  190. /// </summary>
  191. /// <param name="protector">The data protector to use for this operation.</param>
  192. /// <param name="protectedData">The protected data to unprotect.</param>
  193. /// <returns>The plaintext form of the protected data.</returns>
  194. /// <exception cref="System.Security.Cryptography.CryptographicException">
  195. /// Thrown if <paramref name="protectedData"/> is invalid or malformed.
  196. /// </exception>
  197. public static string Unprotect(this IDataProtector protector, string protectedData)
  198. {
  199. if (protector == null)
  200. {
  201. throw new ArgumentNullException(nameof(protector));
  202. }
  203. if (protectedData == null)
  204. {
  205. throw new ArgumentNullException(nameof(protectedData));
  206. }
  207. try
  208. {
  209. byte[] protectedDataAsBytes = WebEncoders.Base64UrlDecode(protectedData);
  210. byte[] plaintextAsBytes = protector.Unprotect(protectedDataAsBytes);
  211. return EncodingUtil.SecureUtf8Encoding.GetString(plaintextAsBytes);
  212. }
  213. catch (Exception ex) when (ex.RequiresHomogenization())
  214. {
  215. // Homogenize exceptions to CryptographicException
  216. throw Error.CryptCommon_GenericError(ex);
  217. }
  218. }
  219. }
  220. }