CA5401:請勿使用具有非預設 IV 的 CreateEncryptor

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

原因

搭配非預設 rgbIV 使用 System.Security.Cryptography.SymmetricAlgorithm.CreateEncryptor

檔案描述

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

此規則類似于 CA5402 ,但分析會判斷初始化向量絕對是預設值。

如何修正違規

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

隱藏警告的時機

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

隱藏警告

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

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

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

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

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

虛擬程式碼範例

using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod(byte[] rgbIV)
    {
        AesCng aesCng  = new AesCng();
        aesCng.IV = rgbIV;
        aesCng.CreateEncryptor();
    }
}

解決方案

using System.Security.Cryptography;

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