Skip to content

scrypt

Header: #include <cryptopp/scrypt.h> | Namespace: CryptoPP Since: Crypto++ 7.0 Thread Safety: DeriveKey() is const and keeps all state local to the call

scrypt is a memory-hard password-based key derivation function specified in RFC 7914, an Informational RFC by Colin Percival and Simon Josefsson. Percival introduced it in the 2009 paper “Stronger Key Derivation via Sequential Memory-Hard Functions”, and it was originally developed for the Tarsnap online backup system. It aims to reduce the advantage that attackers can gain by using custom-designed parallel circuits.

Quick Example

#include <cryptopp/scrypt.h>
#include <cryptopp/secblock.h>
#include <cryptopp/osrng.h>
#include <cryptopp/hex.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    // Password and salt
    std::string password = "correct horse battery staple";

    // Generate random salt (16 bytes minimum recommended)
    AutoSeededRandomPool rng;
    SecByteBlock salt(16);
    rng.GenerateBlock(salt, salt.size());

    // Derive 32-byte key using scrypt
    Scrypt scrypt;
    SecByteBlock derived(32);

    // Parameters: N=2^17, r=8, p=1 (OWASP minimum, 128 MiB)
    scrypt.DeriveKey(
        derived, derived.size(),
        (const byte*)password.data(), password.size(),
        salt, salt.size(),
        131072, // cost (N) - must be power of 2
        8,      // blockSize (r)
        1       // parallelization (p)
    );

    // Display result
    std::string hexOutput;
    StringSource(derived, derived.size(), true,
        new HexEncoder(new StringSink(hexOutput))
    );
    std::cout << "Derived key: " << hexOutput << std::endl;

    return 0;
}

Usage Guidelines

Do:

  • Use at least the OWASP minimum: N=2^17, r=8, p=1
  • Generate random salts (16+ bytes) for each password
  • Store salt and parameters alongside the derived key
  • Consider Argon2id for new applications; OWASP recommends scrypt when Argon2id is not available

Avoid:

  • Using cost (N) values that aren’t powers of 2; the library throws InvalidArgument
  • Relying on the default arguments: the default cost is N=2
  • Using the same salt for multiple passwords
  • Using scrypt for non-password key derivation (use HKDF instead)

Class: Scrypt

Memory-hard key derivation function based on RFC 7914.

Methods

DeriveKey()

size_t DeriveKey(byte* derived, size_t derivedLen,
                 const byte* secret, size_t secretLen,
                 const byte* salt, size_t saltLen,
                 word64 cost = 2,
                 word64 blockSize = 8,
                 word64 parallelization = 1) const;

Derive a key from a password.

Parameters:

  • derived - Output buffer for derived key
  • derivedLen - Length of derived key in bytes
  • secret - Password/passphrase
  • secretLen - Length of password
  • salt - Random salt (should be unique per password)
  • saltLen - Length of salt
  • cost - CPU/memory cost factor N (power of 2; default 2, far too low for passwords)
  • blockSize - Block size r (default: 8)
  • parallelization - Parallelization factor p (default: 1)

Returns: Always returns 1 (number of iterations)

Memory Usage: The array V in scryptROMix holds N blocks of 128 * r bytes, so about 128 * N * r bytes. In an OpenMP build each thread allocates its own V.

Example:

Scrypt scrypt;
SecByteBlock derived(32);

// OWASP minimum: N=2^17, r=8, p=1 (128 MiB)
scrypt.DeriveKey(
    derived, derived.size(),
    (const byte*)password.data(), password.size(),
    salt, salt.size(),
    131072, 8, 1
);

DeriveKey() with NameValuePairs

size_t DeriveKey(byte* derived, size_t derivedLen,
                 const byte* secret, size_t secretLen,
                 const NameValuePairs& params) const;

Alternative interface using named parameters. Missing values fall back to N=2, r=8, p=1 and an empty salt.

Parameters via NameValuePairs:

  • "Salt" - Salt value
  • "Cost" - CPU/memory cost (N)
  • "BlockSize" - Block size (r)
  • "Parallelization" - Parallelization factor (p)

MaxDerivedKeyLength()

size_t MaxDerivedKeyLength() const;

Returns: Maximum derived key length (SIZE_MAX). On platforms with a 64-bit size_t, DeriveKey() still rejects lengths above (2^32-1) * 32 bytes, the RFC 7914 limit.

AlgorithmName()

std::string AlgorithmName() const;

Returns: "scrypt"

Parameter Selection

Understanding scrypt Parameters

ParameterSymbolDescriptionEffect
CostNCPU/memory costMemory = 128 * N * r bytes
BlockSizerBlock sizeIncreases memory per block
ParallelizationpParallelization parameterNumber of independent mixing operations

Recommended Parameters

OWASP gives these minimum settings, which it treats as equivalent:

NrpMemory for V
2^17 (131072)81128 MiB
2^16 (65536)8264 MiB
2^15 (32768)8332 MiB
2^14 (16384)8516 MiB
2^13 (8192)8108 MiB

RFC 7914 says r=8 and p=1 appear to yield good results.

Memory Formula: Memory = 128 * N * r bytes for V

Parameter Constraints

// RFC 7914:
// - N must be larger than 1, a power of 2, and less than 2^(128 * r / 8)
// - p must be a positive integer, at most ((2^32 - 1) * 32) / (128 * r)
// - dkLen must be at most (2^32 - 1) * 32
//
// This library checks:
// - N, r and p are nonzero, and N is a power of 2 (N = 1 is accepted)
// - r * p < 2^30, and p <= INT_MAX
// - derivedLen <= (2^32 - 1) * 32 where size_t is 64-bit

Sources: RFC 7914 sections 2, 5 and 6; the library’s parameter checks. Pass N of at least 2^17 yourself; the library does not enforce the RFC’s N > 1.

Complete Example: Password Hashing and Verification

#include <cryptopp/scrypt.h>
#include <cryptopp/secblock.h>
#include <cryptopp/osrng.h>
#include <cryptopp/misc.h>
#include <iostream>
#include <string>

using namespace CryptoPP;

// OWASP minimum scrypt parameters
const word64 N = 131072;  // Cost (2^17)
const word64 R = 8;       // Block size
const word64 P = 1;       // Parallelization

struct StoredPassword {
    SecByteBlock salt;
    SecByteBlock hash;
};

SecByteBlock deriveHash(const std::string& password, const SecByteBlock& salt) {
    SecByteBlock hash(32);
    Scrypt scrypt;
    scrypt.DeriveKey(
        hash, hash.size(),
        (const byte*)password.data(), password.size(),
        salt, salt.size(),
        N, R, P
    );
    return hash;
}

// Hash a password with a fresh random salt
StoredPassword hashPassword(const std::string& password) {
    AutoSeededRandomPool rng;

    StoredPassword stored;
    stored.salt.New(16);
    rng.GenerateBlock(stored.salt, stored.salt.size());
    stored.hash = deriveHash(password, stored.salt);
    return stored;
}

// Verify a password against a stored salt and hash
bool verifyPassword(const std::string& password,
                    const StoredPassword& stored) {
    SecByteBlock hash = deriveHash(password, stored.salt);

    // Constant-time comparison; the length is not secret
    return hash.size() == stored.hash.size() &&
           VerifyBufsEqual(hash, stored.hash, hash.size());
}

int main() {
    StoredPassword stored = hashPassword("my_secure_password");

    bool accepted = verifyPassword("my_secure_password", stored);
    bool rejected = !verifyPassword("wrong_password", stored);

    std::cout << "Correct password accepted: " << (accepted ? "yes" : "no") << std::endl;
    std::cout << "Wrong password rejected: " << (rejected ? "yes" : "no") << std::endl;

    return (accepted && rejected) ? 0 : 1;
}

The example keeps the salt and hash as bytes and uses one set of cost parameters. An application also stores N, r and p with each record, so they can be raised later, and encodes the record for its database. When it reads parameters back from storage, it sets its own upper limits on them before deriving.

Complete Example: Encryption Key Derivation

#include <cryptopp/scrypt.h>
#include <cryptopp/aes.h>
#include <cryptopp/gcm.h>
#include <cryptopp/osrng.h>
#include <cryptopp/secblock.h>
#include <cryptopp/filters.h>
#include <iostream>

using namespace CryptoPP;

// Derive encryption key from password
SecByteBlock deriveEncryptionKey(const std::string& password,
                                  const SecByteBlock& salt) {
    Scrypt scrypt;
    SecByteBlock key(32);  // AES-256 key

    // OWASP minimum parameters
    scrypt.DeriveKey(
        key, key.size(),
        (const byte*)password.data(), password.size(),
        salt, salt.size(),
        131072,  // N = 2^17 (128 MiB)
        8,       // r = 8
        1        // p = 1
    );

    return key;
}

std::string encryptWithPassword(const std::string& plaintext,
                                 const std::string& password) {
    AutoSeededRandomPool rng;

    // Generate salt and IV
    SecByteBlock salt(16);
    byte iv[12];
    rng.GenerateBlock(salt, salt.size());
    rng.GenerateBlock(iv, sizeof(iv));

    // Derive key
    SecByteBlock key = deriveEncryptionKey(password, salt);

    // Encrypt with AES-GCM
    std::string ciphertext;
    GCM<AES>::Encryption enc;
    enc.SetKeyWithIV(key, key.size(), iv, sizeof(iv));

    StringSource(plaintext, true,
        new AuthenticatedEncryptionFilter(enc,
            new StringSink(ciphertext)
        )
    );

    // Prepend salt and IV to ciphertext
    std::string result;
    result.append((const char*)salt.data(), salt.size());
    result.append((const char*)iv, sizeof(iv));
    result.append(ciphertext);

    return result;
}

int main() {
    std::string message = "Secret message to encrypt";
    std::string password = "user_password";

    std::string encrypted = encryptWithPassword(message, password);

    std::cout << "Encrypted " << message.size() << " bytes -> "
              << encrypted.size() << " bytes" << std::endl;

    return 0;
}

Performance

scrypt’s memory and work grow with N and r; measure on your target hardware. The p loop runs on separate threads only in an OpenMP build; the CMake option CRYPTOPP_USE_OPENMP is off by default.

scrypt vs Other KDFs

KDFMemory-hardOWASP guidance
scryptYesWhen Argon2id is not available
Argon2idYesFirst choice
PBKDF2NoWhere FIPS-140 compliance is required

Security

Security Properties

  • Memory-hard: Offers added protection against attacks using custom hardware
  • Data-dependent memory access: scryptROMix reads V at j = Integerify(X) mod N
  • Built on PBKDF2-HMAC-SHA256 and Salsa20/8 Core: RFC 7914 notes that Salsa20/8 Core is not a cryptographic hash function, since it is not collision resistant
  • Specified in: RFC 7914

Security Notes

  • Salt uniqueness: Always use a unique random salt per password
  • Parameter storage: Store N, r, p alongside the hash for verification
  • Constant-time comparison: Use VerifyBufsEqual() after checking that the lengths match
  • Consider Argon2id: OWASP recommends Argon2id first; it won the Password Hashing Competition

Memory Requirements

Memory for V = 128 * N * r bytes

Examples:
- N=16384,   r=8: 128 * 16384 * 8   = 16,777,216 bytes (16 MiB)
- N=131072,  r=8: 128 * 131072 * 8  = 134,217,728 bytes (128 MiB)
- N=1048576, r=8: 128 * 1048576 * 8 = 1,073,741,824 bytes (1 GiB)

The library also allocates 128 * r * p bytes for B and 256 * r bytes of scratch per thread.

scrypt vs Argon2

FeaturescryptArgon2id
Memory-hardYesYes
Memory accessData-dependentData-independent for the first half of the first pass, then data-dependent
Specified inRFC 7914RFC 9106
Password Hashing CompetitionNot the winnerWinner
OWASP guidanceWhen Argon2id is not availableFirst choice

Recommendation: Use Argon2id for new applications. Use scrypt for compatibility with existing systems that use it, such as Tarsnap.

When to Use scrypt

Use scrypt for:

  1. Compatibility - Systems requiring scrypt, such as Tarsnap
  2. Password Storage - When Argon2 is not available
  3. Key Derivation - Deriving encryption keys from passwords
  4. Existing Systems - Maintaining compatibility with scrypt-based systems

Don’t use scrypt for:

  1. New Applications - Prefer Argon2id
  2. Non-password KDF - Use HKDF for key expansion
  3. Fast Operations - scrypt is intentionally slow
  4. Memory-constrained - Requires significant memory

Exceptions

  • InvalidArgument - N, r or p is 0; N is not a power of 2; r * p is 2^30 or more; p is greater than INT_MAX; or, with a 64-bit size_t, derivedLen is greater than (2^32-1) * 32
  • std::bad_alloc - the buffer sizes for N, r and p overflow size_t
  • InvalidDerivedKeyLength - declared by the interface, but GetValidDerivedLength() accepts every size_t, so it is not thrown

See Also

  • Argon2 - Recommended password hashing (PHC winner)
  • PBKDF2 - Simpler but less secure KDF
  • HKDF - Key expansion (not for passwords)
  • AES-GCM - Authenticated encryption

References

  1. RFC 7914: The scrypt Password-Based Key Derivation Function
  2. Tarsnap: The scrypt key derivation function
  3. OWASP Password Storage Cheat Sheet