Python scrypt Hash Code Example (Online Runner)

Python scrypt key-derivation examples with cost, block size, parallelism, salt encoding, and output length matching the online tool.

Online calculator: use the site scrypt text tool.

Calculation method

Python exposes scrypt in hashlib.scrypt. The online tool’s parameters map to:

  • costn
  • blockSizer
  • parallelismp
  • lengthdklen
  • salt + saltEncoding

Implementation notes

  • Package: built-in hashlib (Python 3.6+).
  • Implementation: the helper maps UI fields directly to n, r, p, and dklen and outputs a hex string.
  • Notes: n must be a power of two and parameters are memory-heavy; large settings can be slow or fail on constrained machines. Always use a unique, random salt for password hashing.
python
import base64
import hashlib
from typing import Literal

SaltEncoding = Literal["base64", "hex"]


def _decode_salt(value: str, encoding: SaltEncoding) -> bytes:
    return base64.b64decode(value) if encoding == "base64" else bytes.fromhex(value)


def scrypt_text(
    text: str,
    cost: int = 16384,
    block_size: int = 8,
    parallelism: int = 1,
    length: int = 64,
    salt: str = "",
    salt_encoding: SaltEncoding = "base64",
) -> str:
    salt_bytes = _decode_salt(salt, salt_encoding) if salt else b"\x00" * 16
    derived = hashlib.scrypt(
        text.encode("utf-8"),
        salt=salt_bytes,
        n=cost,
        r=block_size,
        p=parallelism,
        dklen=length,
    )
    return derived.hex()

# Example usage
print(scrypt_text("password", cost=1024, length=32, salt="73616c74", salt_encoding="hex"))
print(
    scrypt_text(
        "password",
        cost=2048,
        block_size=8,
        parallelism=2,
        length=32,
        salt="c2FsdA==",
        salt_encoding="base64",
    )
)

Complete script (implementation + tests)

python
import hashlib


def run_tests() -> None:
    expected = (
        "745731af4484f323968969eda289aeee005b5903ac561e64a5aca121797bf773"
        "4ef9fd58422e2e22183bcacba9ec87ba0c83b7a2e788f03ce0da06463433cda6"
    )
    actual = hashlib.scrypt(b"password", salt=b"salt", n=16384, r=8, p=1, dklen=64).hex()
    assert actual == expected, "scrypt test vector mismatch"
    print("All scrypt test vectors passed.")


if __name__ == "__main__":
    run_tests()