CA5403:请勿硬编码证书

属性
规则 ID CA5403
标题 请勿硬编码证书
类别 安全性
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用

原因

X509CertificateX509Certificate2 构造函数的 datarawData 参数由以下内容之一进行硬编码:

规则说明

硬编码证书的私钥很轻松就可以发现。 即使使用已编译的二进制文件,恶意用户也很容易提取硬编码证书的私钥。 私钥泄露后,攻击者便可以模拟该证书,受该证书保护的任何资源或操作都将提供给攻击者。

如何解决冲突

  • 考虑重新设计应用程序,以使用安全的密钥管理系统,如 Azure Key Vault。
  • 将凭据和证书保留在安全位置,与源代码分开。

何时禁止显示警告

如果硬编码数据不包含证书的私钥,可禁止显示此规则的警告。 例如,数据来自 .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);
    }
}

由字符数组硬编码

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