Python Scrypt Bindings

0.9.4 · active · verified Thu Apr 16

The `scrypt` library provides Python bindings for the scrypt key derivation function, which is designed to make brute-force attacks on password hashes more difficult by requiring more memory and CPU. It's commonly used for securely hashing passwords. The current version is 0.9.4, with minor releases occurring periodically to address bug fixes and build improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to hash a password using `scrypt.hash()` and verify it with `scrypt.verify()`. It highlights the importance of `N`, `r`, and `p` parameters and the use of cryptographically secure random salts. Inputs (password and salt) must be `bytes`.

import scrypt
import os

# --- Parameters for scrypt (N, r, p) ---
# N: CPU/Memory cost parameter (must be a power of 2, e.g., 2**14 = 16384)
#    Higher N means more work, increasing security against brute-force attacks.
# r: Block size parameter
# p: Parallelization parameter
# Choosing these values appropriately is critical for security and performance.
# For production, recommended values are often N=2**14 to 2**20, r=8, p=1.
# Values too high can cause excessive memory/CPU usage, potentially leading to DoS.
N = 16384  # 2**14
r = 8
p = 1

password = b"my_super_secret_password"
# Generate a cryptographically secure random salt (at least 16 bytes)
salt = os.urandom(16)

try:
    # 1. Hash the password
    # The hash function returns bytes
    hashed_password_bytes = scrypt.hash(password, salt, N, r, p)
    print(f"Scrypt hash (hex): {hashed_password_bytes.hex()}")

    # 2. Verify the password
    # For verification, the original password, salt, and parameters (N, r, p)
    # used during hashing must be provided.
    is_valid = scrypt.verify(password, hashed_password_bytes, salt, N, r, p)
    print(f"Password verification successful: {is_valid}")

    # Example of a wrong password
    wrong_password = b"wrong_password"
    try:
        scrypt.verify(wrong_password, hashed_password_bytes, salt, N, r, p)
        print("Verification with wrong password succeeded (ERROR!)")
    except scrypt.error:
        print("Verification with wrong password failed (EXPECTED)")

except scrypt.error as e:
    print(f"An scrypt error occurred: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

# In a real application, you would store the salt and N, r, p parameters
# alongside the hash (e.g., as part of a standard scrypt format string like $s0$...)
# The 'scrypt' library does not provide this format string generation directly;
# you need to implement that logic yourself or use a higher-level library.

view raw JSON →