C Sharp X509certificate2 Privatekey Used
Description
Detects insecure handling of private keys in X509Certificate2 objects in C# code. When the PrivateKey property of an X509Certificate2 object is accessed directly, it can expose sensitive cryptographic material that should be protected. This poses a security risk as exposed private keys can be compromised and used to decrypt sensitive data or forge digital signatures.
Detection Strategy
• Check if the System.Security.Cryptography namespace is imported in the code
• Look for direct access to the 'PrivateKey' property on X509Certificate2 objects
• Verify that the object being accessed is an X509Certificate2 instance
• Report a vulnerability when PrivateKey property access is found on an X509Certificate2 object
Vulnerable code example
using System.Security.Cryptography;
class UnsafeCertAccess {
static void Main() {
var cert = new X509Certificate2();
var key = cert.PrivateKey; // Vulnerable: Direct access to private key without security checks
}
}✅ Secure code example
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
class SafeCertAccess {
static void Main() {
try {
// Use secure flag combination to protect key material
var cert = new X509Certificate2("cert.pfx", "password", ...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.