CA5403:不要硬式編碼憑證

屬性
規則識別碼 CA5403
標題 不要硬式編碼憑證
類別 安全性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

X509Certificate2data構函式的 X509CertificaterawData 參數是由下列其中一項硬式編碼:

檔案描述

可以輕鬆地探索硬式編碼憑證的私鑰。 即使使用編譯的二進位檔,惡意使用者也很容易擷取硬式編碼憑證的私鑰。 一旦私鑰遭到入侵,攻擊者就可以模擬該憑證,而該憑證所保護的任何資源或作業都將可供攻擊者使用。

如何修正違規

  • 請考慮重新設計應用程式以使用安全密鑰管理系統,例如 Azure 金鑰保存庫。
  • 將認證和憑證保留在與原始程式碼分開的安全位置。

隱藏警告的時機

如果硬式編碼的數據未包含憑證的私鑰,則隱藏此規則的警告是安全的。 例如,數據來自檔案 .cer 。 硬式編碼的公開憑證資訊在憑證到期或遭到撤銷時,仍可能會造成輪替憑證的挑戰。

隱藏警告

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

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

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

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

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

虛擬程式代碼範例

硬式編碼位元組陣列

using System.IO;
using System.Security.Cryptography.X509Certificates;

class ExampleClass
{
    public void ExampleMethod(string path)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate2(path);
    }
}

以 char 陣列硬式編碼

using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;

class ExampleClass
{
    public void ExampleMethod(byte[] bytes, string path)
    {
        char[] chars = new char[] { '1', '2', '3' };
        Encoding.ASCII.GetBytes(chars, 0, 3, bytes, 0);
        File.WriteAllBytes(path, bytes);
        new X509Certificate2(path);
    }
}

由 FromBase64String 硬式編碼

using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;

class ExampleClass
{
    public void ExampleMethod(string path)
    {
        byte[] bytes = Convert.FromBase64String("AAAAAaazaoensuth");
        File.WriteAllBytes(path, bytes);
        new X509Certificate2(path);
    }
}

由 GetBytes 硬式編碼

using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;

class ExampleClass
{
    public void ExampleMethod(string path)
    {
        byte[] bytes = Encoding.ASCII.GetBytes("AAAAAaazaoensuth");
        File.WriteAllBytes(path, bytes);
        new X509Certificate2(path);
    }
}

解決方案

using System.IO;
using System.Security.Cryptography.X509Certificates;

class ExampleClass
{
    public void ExampleMethod(string path)
    {
        new X509Certificate2("Certificate.cer");
    }
}