Gaoyang's Blog
Gaoyang's Blog
/
🍹
如何在 C# 中实现 EVP_PBE_scrypt 函数
Search
如何在 C# 中实现 EVP_PBE_scrypt 函数
🍹

如何在 C# 中实现 EVP_PBE_scrypt 函数

Tags
C#
OpenSSL
Published
February 24, 2023
Author
gaoyang
EVP_PBE_scrypt 是 OpenSSL 提供的基于 scrypt 算法的密钥派生函数(KDF)。在 C# / .NET 中如果不想自己手写底层算法,通常有两种落地方案:直接用托管库 BouncyCastle,或者通过 P/Invoke 调用本地 OpenSSL 动态库。

方式一:使用 BouncyCastle(推荐)

如果只需要标准的 scrypt 派生结果、且希望保持纯托管代码跨平台运行,直接安装 BouncyCastle.Cryptography(老项目常见 Portable.BouncyCastle)是最省心的:
dotnet add package BouncyCastle.Cryptography
直接调用 SCrypt.Generate 即可:
using System.Text; using Org.BouncyCastle.Crypto.Generators; public static byte[] DeriveKeyWithScrypt( string password, byte[] salt, int cost = 0x8000, // N: CPU/内存开销参数,必须为 2 的幂 int blockSize = 8, // r: 块大小 int parallelization = 2,// p: 并行度 int keyLength = 32) // 派生密钥字节长度 { var passwordBytes = Encoding.UTF8.GetBytes(password); return SCrypt.Generate(passwordBytes, salt, cost, blockSize, parallelization, keyLength); }
注意:SCrypt.Generate 的参数顺序与 OpenSSL 一致,都是 (password, salt, N, r, p, dkLen)。其中 N 必须是大于 1 的 2 的幂,且内存占用大约为 128 * N * r 字节,参数给太大时要注意内存上限。

方式二:通过 P/Invoke 调用 OpenSSL

如果项目本身已经随包分发了 OpenSSL,或者需要严格对齐 OpenSSL 的 maxmem 限制行为,可以通过 P/Invoke 直接调用 EVP_PBE_scrypt。
在 OpenSSL 1.1+ / 3.x 中,函数位于 libcrypto(Windows 下常见 libcrypto-3-x64.dll 或 libcrypto-1_1-x64.dll,Linux 为 libcrypto.so,macOS 为 libcrypto.dylib;只有非常老的 OpenSSL 1.0.x 才叫 libeay32.dll)。
using System.Runtime.InteropServices; public static class OpenSslNative { // 按目标平台与 OpenSSL 版本替换为对应的动态库名,如 libcrypto-3-x64.dll / libcrypto.so private const string LibCrypto = "libcrypto-3-x64.dll"; [DllImport(LibCrypto, CallingConvention = CallingConvention.Cdecl)] public static extern int EVP_PBE_scrypt( byte[] pass, nuint passlen, byte[] salt, nuint saltlen, ulong N, ulong r, ulong p, ulong maxmem, byte[] key, nuint keylen); }
几点踩坑提示:
  • C 原型中 passlen、saltlen、keylen 类型是 size_t,在 C# 里建议用 nuint(或 UIntPtr),避免 64 位平台上用 int 导致栈/寄存器截断。
  • pass 建议直接传 UTF-8 编码后的 byte[] 而不是 string,避免默认 ANSI 编组或包含 \0 字节时结果不一致。
  • EVP_PBE_scrypt 返回 1 表示成功,0 表示失败(例如所需内存超过 maxmem;传 0 表示使用 OpenSSL 默认的 32MB 上限)。
Copyright 2026 gaoyang