pbe_scrypt.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <openssl/evp.h>
  10. #include <openssl/err.h>
  11. #include <openssl/kdf.h>
  12. #include <openssl/core_names.h>
  13. #include "internal/numbers.h"
  14. #ifndef OPENSSL_NO_SCRYPT
  15. /*
  16. * Maximum permitted memory allow this to be overridden with Configuration
  17. * option: e.g. -DSCRYPT_MAX_MEM=0 for maximum possible.
  18. */
  19. #ifdef SCRYPT_MAX_MEM
  20. # if SCRYPT_MAX_MEM == 0
  21. # undef SCRYPT_MAX_MEM
  22. /*
  23. * Although we could theoretically allocate SIZE_MAX memory that would leave
  24. * no memory available for anything else so set limit as half that.
  25. */
  26. # define SCRYPT_MAX_MEM (SIZE_MAX/2)
  27. # endif
  28. #else
  29. /* Default memory limit: 32 MB */
  30. # define SCRYPT_MAX_MEM (1024 * 1024 * 32)
  31. #endif
  32. int EVP_PBE_scrypt(const char *pass, size_t passlen,
  33. const unsigned char *salt, size_t saltlen,
  34. uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
  35. unsigned char *key, size_t keylen)
  36. {
  37. const char *empty = "";
  38. int rv = 1;
  39. EVP_KDF *kdf;
  40. EVP_KDF_CTX *kctx;
  41. OSSL_PARAM params[7], *z = params;
  42. if (r > UINT32_MAX || p > UINT32_MAX) {
  43. EVPerr(EVP_F_EVP_PBE_SCRYPT, EVP_R_PARAMETER_TOO_LARGE);
  44. return 0;
  45. }
  46. /* Maintain existing behaviour. */
  47. if (pass == NULL) {
  48. pass = empty;
  49. passlen = 0;
  50. }
  51. if (salt == NULL) {
  52. salt = (const unsigned char *)empty;
  53. saltlen = 0;
  54. }
  55. if (maxmem == 0)
  56. maxmem = SCRYPT_MAX_MEM;
  57. kdf = EVP_KDF_fetch(NULL, OSSL_KDF_NAME_SCRYPT, NULL);
  58. kctx = EVP_KDF_CTX_new(kdf);
  59. EVP_KDF_free(kdf);
  60. if (kctx == NULL)
  61. return 0;
  62. *z++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD,
  63. (unsigned char *)pass,
  64. passlen);
  65. *z++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
  66. (unsigned char *)salt, saltlen);
  67. *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_N, &N);
  68. *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_R, &r);
  69. *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_P, &p);
  70. *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_MAXMEM, &maxmem);
  71. *z = OSSL_PARAM_construct_end();
  72. if (EVP_KDF_CTX_set_params(kctx, params) != 1
  73. || EVP_KDF_derive(kctx, key, keylen) != 1)
  74. rv = 0;
  75. EVP_KDF_CTX_free(kctx);
  76. return rv;
  77. }
  78. #endif