---
title: "Derive an encryption key with scrypt in C#"
url: https://recursiveai.org/onecrypto/cookbook/derive-key-with-scrypt/
description: "Derive a 32-byte encryption key from a password in C# with scrypt and a random salt. Run the example and check its output against RFC 7914."
version: "0.4.0-preview.2"
---

# Derive an encryption key with scrypt in C#

**OneCrypto** is a free, open-source cryptography library for .NET from Recursive AI. MIT or Apache-2.0, preview, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneCrypto) · [GitHub](https://github.com/recursive-ai-oss/onecrypto-csharp) · [Docs](https://recursiveai.org/onecrypto/docs/) · [Download example (.zip)](https://recursiveai.org/onecrypto/cookbook/derive-key-with-scrypt/derive-key-with-scrypt.zip)

Pass a password and a fresh salt to `Scrypt.DeriveKey`.

```shell
dotnet add package RecursiveAI.OneCrypto --prerelease
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using System.Security.Cryptography;
using RecursiveAI.OneCrypto.Primitives;
var salt = RandomNumberGenerator.GetBytes(16);
byte[] key = Scrypt.DeriveKey(
    "demo passphrase"u8, salt,
    cost: 131072, blockSize: 8,
    parallelism: 1, length: 32);
Console.WriteLine($"Derived {key.Length} bytes.");
CryptographicOperations.ZeroMemory(key);
```

Unzip [the example](https://recursiveai.org/onecrypto/cookbook/derive-key-with-scrypt/derive-key-with-scrypt.zip), then `dotnet run`.

```text
Derived 32 bytes.
```

## Full program

```csharp
using System.Security.Cryptography;
using RecursiveAI.OneCrypto.Primitives;

var salt = RandomNumberGenerator.GetBytes(16);
byte[] key = Scrypt.DeriveKey(
    "demo passphrase"u8, salt,
    cost: 131072, blockSize: 8,
    parallelism: 1, length: 32);
Console.WriteLine($"Derived {key.Length} bytes.");
CryptographicOperations.ZeroMemory(key);

// RFC 7914 §12: public inputs, not settings for new encryption.
byte[] vector = Scrypt.DeriveKey(
    "password"u8, "NaCl"u8, 1024, 8, 16, 64);
byte[] expected = Convert.FromHexString(
    "FDBABE1C9D3472007856E7190D01E9FE" +
    "7C6AD7CBC8237830E77376634B373162" +
    "2EAF30D92E22A3886FF109279D9830DA" +
    "C727AFB94A83EE6D8360CBDFA2CC0640");
if (!vector.AsSpan().SequenceEqual(expected))
    throw new InvalidOperationException("scrypt vector mismatch.");
Console.WriteLine("RFC 7914 vector: match.");
```

```text
Derived 32 bytes.
RFC 7914 vector: match.
```

The first call uses a fresh salt and prints the key length, not the key. The second call compares all 64 bytes of the [RFC 7914 §12 vector](https://www.rfc-editor.org/rfc/rfc7914.html#section-12), using its public inputs rather than the settings from the first call. In an application, pass the key to [`AesGcm`](https://learn.microsoft.com/dotnet/api/system.security.cryptography.aesgcm.-ctor) and encrypt before clearing it. Keep the key out of logs, and save the salt and settings with the ciphertext.

Invalid parameters throw `ArgumentException` or `ArgumentOutOfRangeException`; a valid request that exceeds OneCrypto’s work or memory bounds throws `KdfLimitExceededException`.

## Variations

**Write a 16-byte key into a buffer you supply.** Replace the lines from `byte[] key` onward in the snippet at the top:

```csharp
Span<byte> key = stackalloc byte[16];
Scrypt.DeriveKey(
    "demo passphrase"u8, salt, 131072, 8, 1, key);
Console.WriteLine($"Derived {key.Length} bytes.");
CryptographicOperations.ZeroMemory(key);
```

```text
Derived 16 bytes.
```

## Related recipes

- [Hash and verify passwords with Argon2id](https://recursiveai.org/onecrypto/cookbook/argon2-password-hashing/)
- [Derive OpenSSH key material with bcrypt-pbkdf](https://recursiveai.org/onecrypto/cookbook/derive-openssh-key-with-bcrypt-pbkdf/)

## The short answer

In C#, call `Scrypt.DeriveKey` with the password bytes, salt, `N`, `r`, `p`, and the required output length in bytes. Use the length your cipher expects: for example, 32 bytes for AES-256. The call derives key material; it doesn’t encrypt anything. To decrypt later, use the same inputs to derive the same key.

## What is the scrypt algorithm and how does it work?

[scrypt](https://www.rfc-editor.org/rfc/rfc7914.html#section-6) is a password-based key derivation function. It uses PBKDF2 with HMAC-SHA-256 before and after a mixing step that builds and reads a table in memory. A password guess has to pay for that work too. Hashing the passphrase with SHA-256 alone would give you 32 bytes, but it would skip the work that makes repeated guesses more expensive.

`N` sets the CPU and memory cost and must be a power of two greater than one. `r` sets the block size. Together, they make the main mixing table `128 × N × r` bytes; `N = 131072` and `r = 8` make that table 128 MiB before other buffers. `p` controls the number of blocks that go through the mix. OneCrypto runs them on one thread, so `p = 16` in the test vector does not mean 16 threads. Use the input format’s parameters when reading existing data, and choose and measure settings against your memory budget and expected concurrency when designing new data. OneCrypto’s [KDF settings](https://recursiveai.org/onecrypto/docs/kdf/) let you bound how much work an input can request before the library allocates the working buffers.

## What is password salting and how does it work?

A salt is a public input, separate from the password. Generate a fresh random salt for each new derivation so two files encrypted from the same passphrase need not use the same key. Store the salt, the algorithm, and the cost parameters alongside the ciphertext. Keep the derived key and passphrase secret. A salt does not replace a cipher’s nonce or IV: if the encryption format calls for either, keep following that format’s rules.

Match the password bytes as well as the text. The C# `u8` literals in the recipe are UTF-8 byte sequences. For existing data, use the encoding and any normalization its format expects; a change to those bytes changes the input to scrypt. For a login database, the goal is different: store a password verifier, not a key to decrypt something. The [Argon2id recipe](https://recursiveai.org/onecrypto/cookbook/argon2-password-hashing/) shows that workflow.
