KeyDerivation.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2;
  5. namespace Microsoft.AspNetCore.Cryptography.KeyDerivation
  6. {
  7. /// <summary>
  8. /// Provides algorithms for performing key derivation.
  9. /// </summary>
  10. public static class KeyDerivation
  11. {
  12. /// <summary>
  13. /// Performs key derivation using the PBKDF2 algorithm.
  14. /// </summary>
  15. /// <param name="password">The password from which to derive the key.</param>
  16. /// <param name="salt">The salt to be used during the key derivation process.</param>
  17. /// <param name="prf">The pseudo-random function to be used in the key derivation process.</param>
  18. /// <param name="iterationCount">The number of iterations of the pseudo-random function to apply
  19. /// during the key derivation process.</param>
  20. /// <param name="numBytesRequested">The desired length (in bytes) of the derived key.</param>
  21. /// <returns>The derived key.</returns>
  22. /// <remarks>
  23. /// The PBKDF2 algorithm is specified in RFC 2898.
  24. /// </remarks>
  25. public static byte[] Pbkdf2(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested)
  26. {
  27. if (password == null)
  28. {
  29. throw new ArgumentNullException(nameof(password));
  30. }
  31. if (salt == null)
  32. {
  33. throw new ArgumentNullException(nameof(salt));
  34. }
  35. // parameter checking
  36. if (prf < KeyDerivationPrf.HMACSHA1 || prf > KeyDerivationPrf.HMACSHA512)
  37. {
  38. throw new ArgumentOutOfRangeException(nameof(prf));
  39. }
  40. if (iterationCount <= 0)
  41. {
  42. throw new ArgumentOutOfRangeException(nameof(iterationCount));
  43. }
  44. if (numBytesRequested <= 0)
  45. {
  46. throw new ArgumentOutOfRangeException(nameof(numBytesRequested));
  47. }
  48. return Pbkdf2Util.Pbkdf2Provider.DeriveKey(password, salt, prf, iterationCount, numBytesRequested);
  49. }
  50. }
  51. }