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 的單次靜態方法。

例如,修改以下程式碼:

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

對此:

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

如果你使用的Rfc2898DeriveBytes建構函式需要一個鹽值大小,你需要手動創建鹽值,因為Rfc2898DeriveBytes.Pbkdf2沒有接受鹽值大小的重載函式。 為了與先前實作保持一致,可以用 RandomNumberGenerator.Fill 加密安全的位元組填滿現有陣列,或 RandomNumberGenerator.GetBytes 建立一個包含加密安全位元組的新陣列。

例如,修改以下程式碼:

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

對此:

byte[] salt = RandomNumberGenerator.GetBytes(saltSize);
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>

如需詳細資訊,請參閱 隱藏警告。