.NET Framework 4.6.1中Rfc2898DeriveBytes四参构造函数报错问题
问题原因及解决方案
核心原因
你遇到的CS1729错误本质是目标框架版本不匹配:
- 带
HashAlgorithmName参数的Rfc2898DeriveBytes四参数构造函数,是在**.NET Framework 4.7及更高版本**才新增的API; - 你的项目目标框架是4.6.1,该版本的
Rfc2898DeriveBytes仅提供以下构造函数:Rfc2898DeriveBytes(string password, byte[] salt)Rfc2898DeriveBytes(string password, byte[] salt, int iterations)Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations)
- 你看到的“存在该构造函数”,大概率是查看了高版本框架的文档或本地引用了高版本程序集,但项目编译时仍以4.6.1的API为准。
解决方案
方案1:升级项目目标框架
如果项目允许,直接将目标框架升级到.NET Framework 4.7及以上:
- 右键项目 → 属性 → 应用程序 → 目标框架,选择4.7/4.7.1等更高版本;
- 重新编译后即可正常调用四参数构造函数:
var deriveBytes = new Rfc2898DeriveBytes(password, salt, 100000, HashAlgorithmName.SHA512);
方案2:不升级框架,手动实现PBKDF2-HMAC-SHA512
若无法升级框架,需要自行实现PBKDF2算法结合HMACSHA512,示例代码如下:
using System; using System.Security.Cryptography; public static byte[] Pbkdf2Sha512(byte[] password, byte[] salt, int iterations, int outputLength) { using (var hmac = new HMACSHA512(password)) { int hashLength = hmac.HashSize / 8; if (outputLength % hashLength != 0) throw new ArgumentException("输出长度必须是哈希长度的整数倍"); int blockCount = outputLength / hashLength; byte[] result = new byte[outputLength]; for (int i = 1; i <= blockCount; i++) { byte[] block = BitConverter.GetBytes(i); Array.Reverse(block); // 转换为大端字节序 // 第一个迭代:HMAC(salt + block) byte[] u = hmac.ComputeHash(Combine(salt, block)); byte[] temp = u; // 后续迭代:HMAC(u_prev) for (int j = 1; j < iterations; j++) { u = hmac.ComputeHash(u); for (int k = 0; k < u.Length; k++) temp[k] ^= u[k]; } Buffer.BlockCopy(temp, 0, result, (i - 1) * hashLength, hashLength); } return result; } } private static byte[] Combine(byte[] a, byte[] b) { byte[] result = new byte[a.Length + b.Length]; Buffer.BlockCopy(a, 0, result, 0, a.Length); Buffer.BlockCopy(b, 0, result, a.Length, b.Length); return result; }
使用时直接调用该方法即可生成SHA512哈希的PBKDF2结果。
内容的提问来源于stack exchange,提问作者peter
相关产品推荐
相关产品推荐

