SYSLIB0060:Rfc2898DeriveBytes 构造函数已过时

从 .NET 10 开始,System.Security.Cryptography.Rfc2898DeriveBytes 上的所有构造函数都已过时。 在代码中调用这些构造函数会在编译时生成警告 SYSLIB0060

过时的原因

System.Security.Cryptography.Rfc2898DeriveBytes 提供的基于实例的 PBKDF2 实现通过允许连续调用 GetBytes,来以流方式处理字节,从而带来一种非标准的用法。 这不是 PBKDF2 的预期用途,算法应当一次性完成计算。 一次性功能由静态方法 Rfc2898DeriveBytes.Pbkdf2 实现,应使用该方法,而不是实例化 System.Security.Cryptography.Rfc2898DeriveBytes

解决方法

更改 System.Security.Cryptography.Rfc2898DeriveBytes 的实例并调用 GetBytes,以改用 Rfc2898DeriveBytes.Pbkdf2 一次性静态方法。

例如,更改:

using System.Security.Cryptography;

Rfc2898DeriveBytes kdf = new Rfc2898DeriveBytes(password, salt, iterations, hashAlgorithm);
byte[] derivedKey = kdf.GetBytes(64);

接收方

byte[] derivedKey = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, hashAlgorithm, 64);

禁止显示警告

如果必须使用过时的 API,可以在代码或项目文件中禁止显示警告。

若要仅取消单个冲突,请将预处理器指令添加到源文件以禁用,然后重新启用警告。

// Disable the warning.
#pragma warning disable SYSLIB0060

// Code that uses obsolete API.
// ...

// Re-enable the warning.
#pragma warning restore SYSLIB0060

若要取消项目中的所有 SYSLIB0060 警告,请将 <NoWarn> 属性添加到项目文件。

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
   ...
   <NoWarn>$(NoWarn);SYSLIB0060</NoWarn>
  </PropertyGroup>
</Project>

有关详细信息,请参阅 禁止显示警告