2 * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
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
10 #include <openssl/evp.h>
11 #include <openssl/err.h>
12 #include <openssl/kdf.h>
13 #include <openssl/core_names.h>
14 #include "internal/numbers.h"
16 #ifndef OPENSSL_NO_SCRYPT
19 * Maximum permitted memory allow this to be overridden with Configuration
20 * option: e.g. -DSCRYPT_MAX_MEM=0 for maximum possible.
24 # if SCRYPT_MAX_MEM == 0
25 # undef SCRYPT_MAX_MEM
27 * Although we could theoretically allocate SIZE_MAX memory that would leave
28 * no memory available for anything else so set limit as half that.
30 # define SCRYPT_MAX_MEM (SIZE_MAX/2)
33 /* Default memory limit: 32 MB */
34 # define SCRYPT_MAX_MEM (1024 * 1024 * 32)
37 int EVP_PBE_scrypt(const char *pass, size_t passlen,
38 const unsigned char *salt, size_t saltlen,
39 uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
40 unsigned char *key, size_t keylen)
42 const char *empty = "";
46 OSSL_PARAM params[7], *z = params;
48 if (r > UINT32_MAX || p > UINT32_MAX) {
49 EVPerr(EVP_F_EVP_PBE_SCRYPT, EVP_R_PARAMETER_TOO_LARGE);
53 /* Maintain existing behaviour. */
59 salt = (const unsigned char *)empty;
63 maxmem = SCRYPT_MAX_MEM;
65 kdf = EVP_KDF_fetch(NULL, OSSL_KDF_NAME_SCRYPT, NULL);
66 kctx = EVP_KDF_CTX_new(kdf);
71 *z++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD,
72 (unsigned char *)pass,
74 *z++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
75 (unsigned char *)salt, saltlen);
76 *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_N, &N);
77 *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_R, &r);
78 *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_P, &p);
79 *z++ = OSSL_PARAM_construct_uint64(OSSL_KDF_PARAM_SCRYPT_MAXMEM, &maxmem);
80 *z = OSSL_PARAM_construct_end();
81 if (EVP_KDF_CTX_set_params(kctx, params) != 1
82 || EVP_KDF_derive(kctx, key, keylen) != 1)
85 EVP_KDF_CTX_free(kctx);