CA5379: キー派生関数アルゴリズムが十分に強力であることを確認します

プロパティ
ルール ID CA5379
Title キー派生関数アルゴリズムが十分に強力であることを確認します
[カテゴリ] Security
修正が中断か中断なしであるか なし
.NET 8 では既定で有効 いいえ

原因

System.Security.Cryptography.Rfc2898DeriveBytes をインスタンス化するとき、次のアルゴリズムのいずれかを使用しました。

規則の説明

Rfc2898DeriveBytes クラスでは、既定で SHA1 アルゴリズムを使用します。 Rfc2898DeriveBytes オブジェクトをインスタンス化するとき、SHA256 以上のハッシュ アルゴリズムを指定する必要があります。 Rfc2898DeriveBytes.HashAlgorithm プロパティのアクセサーは get だけであることにご注意ください。

違反の修正方法

MD5 または SHA1 は競合に対して脆弱であるため、Rfc2898DeriveBytes クラスには SHA256 以上を使用してください。

.NET Framework または .NET Core のバージョンが古いと、キー派生関数ハッシュ アルゴリズムを指定できないことがあります。 そのような場合、もっと強力なアルゴリズムを使用するため、.NET のターゲット フレームワーク バージョンをアップグレードする必要があります。

どのようなときに警告を抑制するか

アプリケーションの互換性が理由ではない限り、この規則を抑制することは推奨されません。

警告を抑制する

単一の違反を抑制するだけの場合は、ソース ファイルにプリプロセッサ ディレクティブを追加して無効にしてから、規則をもう一度有効にします。

#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);
    }
}