Do not hard-code certificate
Do not hard-code certificate
Microsoft docsDescription
A hard-coded certificate's private key is easily discovered. Even with compiled binaries, it is easy for malicious users to extract a hard-coded certificate's private key. Once the private key is compromised, an attacker can impersonate that certificate, and any resources or operations protected by that certificate will be available to the attacker.
Cause
The data or rawData parameter of a System.Security.Cryptography.X509Certificates.X509Certificate or System.Security.Cryptography.X509Certificates.X509Certificate2 constructor is hard-coded by one of the following:
- Byte array.
- Char array.
- System.Convert.FromBase64String(System.String).
- All the overloads of System.Text.Encoding.GetBytes.
How to fix violations
- Consider redesigning your application to use a secure key management system, such as Azure Key Vault.
- Keep credentials and certificates in a secure location separate from your source code.
Example
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);
}
}
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);
}
}
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");
}
}When to suppress
It's safe to suppress a warning from this rule if the hard-coded data doesn't contain the certificate's private key. For example, the data is from a .cer file. Hard-coding public certificate information may still create a challenge for rotating certificates as they expire or get revoked.