CA5402:使用具有預設 IV 的 CreateEncryptor

屬性
規則識別碼 CA5402
標題 使用具有預設 IV 的 CreateEncryptor
類別 安全性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

rgbIV使用 System.Security.Cryptography.SymmetricAlgorithm.CreateEncryptor時,可能是非預設值。

檔案描述

對稱式加密應一律使用不可重複的初始化向量來防止字典攻擊。

此規則類似於 CA5401,但分析無法判斷初始化向量絕對為預設值。

如何修正違規

明確使用預設值 rgbIV ,也就是使用 沒有任何參數的 System.Security.Cryptography.SymmetricAlgorithm.CreateEncryptor 多載。

隱藏警告的時機

如果下列狀況,可以放心地隱藏此規則的警告:

隱藏警告

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

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

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

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

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

虛擬程式代碼範例

using System;
using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod(byte[] rgbIV)
    {
        AesCng aesCng  = new AesCng();
        Random r = new Random();

        if (r.Next(6) == 4)
        {
            aesCng.IV = rgbIV;
        }

        aesCng.CreateEncryptor();
    }
}

解決方案

using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod()
    {
        AesCng aesCng  = new AesCng();
        aesCng.CreateEncryptor();
    }
}