CA5379:確定密鑰衍生函式演算法足夠強

屬性
規則識別碼 CA5379
標題 確定密鑰衍生函式演算法足夠強
類別 安全性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

具現化 System.Security.Cryptography.Rfc2898DeriveBytes時,使用下列其中一個演算法:

檔案描述

Rfc2898DeriveBytes 類別預設為使用 SHA1 演算法。 具現化 Rfc2898DeriveBytes 物件時,您應該指定 或更新版本的哈希演算法 SHA256 。 請注意, Rfc2898DeriveBytes.HashAlgorithm 屬性只有 存取 get 子。

如何修正違規

因為 MD5SHA1 容易發生衝突,因此請針對 Rfc2898DeriveBytes 類別使用 SHA256 或更新版本。

舊版 .NET Framework 或 .NET Core 可能不允許您指定密鑰衍生函式哈希演算法。 在這種情況下,您必須升級 .NET 的目標 Framework 版本,才能使用更強的演算法。

隱藏警告的時機

除了應用程式相容性原因之外,不建議隱藏此規則。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable CA5379
// The code that's violating the rule is on this line.
#pragma warning restore CA5379

若要停用檔案、資料夾或項目的規則,請在組態檔中將其嚴重性設定為 。none

[*.{cs,vb}]
dotnet_diagnostic.CA5379.severity = none

如需詳細資訊,請參閱 如何隱藏程式代碼分析警告

虛擬程式代碼範例

在建構函式違規中指定哈希演算法

using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod(byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm)
    {
        var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, iterations, HashAlgorithmName.MD5);
    }
}

在衍生類別的建構函式違規中指定哈希演算法

using System.Security.Cryptography;

class DerivedClass : Rfc2898DeriveBytes
{
    public DerivedClass (byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm) : base(password, salt, iterations, hashAlgorithm)
    {
    }
}

class ExampleClass
{
    public void ExampleMethod(byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm)
    {
        var derivedClass = new DerivedClass(password, salt, iterations, HashAlgorithmName.MD5);
    }
}

在衍生類別違規中設定哈希演算法屬性

using System.Security.Cryptography;

class DerivedClass : Rfc2898DeriveBytes
{
    public DerivedClass (byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm) : base(password, salt, iterations, hashAlgorithm)
    {
    }

    public HashAlgorithmName HashAlgorithm { get; set;}
}

class ExampleClass
{
    public void ExampleMethod(byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm)
    {
        var derivedClass = new DerivedClass(password, salt, iterations, HashAlgorithmName.MD5);
        derivedClass.HashAlgorithm = HashAlgorithmName.SHA256;
    }
}

解決方案

using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod(byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm)
    {
        var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, iterations, HashAlgorithmName.SHA256);
    }
}