Skip to content

Error reading exported certificate private key on some machines. #109886

@Marcioztec

Description

@Marcioztec

Description

On several machines with new and old Windows 10/11, an error is occurring when requesting the private key of a previously exported certificate.

Reproduction Steps

//code for testing
using System;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Text;

public class Program
{
	public static void Main()
	{ 
		string password = "F@dr4PaeE#2a";
		byte[] certData;
		StringBuilder dn = new StringBuilder();
		dn.Append("CN=64d9f3dd-23ba-0101-a802-a4893a4b9695,O=TESTE,OU=Gene,L=Realeza,S=PR,C=BR");
		X500DistinguishedName d = new X500DistinguishedName(dn.ToString());
		using (RSA a = RSA.Create(2048))
		{
			CertificateRequest r3 = new CertificateRequest(d, a, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
			 r3.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyCertSign, false));
			r3.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection {
				new Oid("1.3.6.1.5.5.7.3.8"),
				new Oid("1.3.6.1.5.5.7.3.2"),
			}, false));
			
			SubjectAlternativeNameBuilder ss = new SubjectAlternativeNameBuilder();
			r3.CertificateExtensions.Add(ss.Build());
			X509Certificate2 objCert = r3.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.Date), new DateTimeOffset(DateTime.UtcNow.AddYears(1)));

			 RSA keyw = objCert.GetRSAPrivateKey();
			 Console.WriteLine("1 " + keyw.ExportSubjectPublicKeyInfoPem());
			 Console.WriteLine("1 " + keyw.ExportPkcs8PrivateKeyPem());//ok works
			certData = objCert.Export(X509ContentType. Pfx, password);
		}
		X509Certificate2 objCertificado = new X509Certificate2(certData, password);
		RSA aww = objCertificado.GetRSAPrivateKey();
		Console.WriteLine("2 " + aww.ExportSubjectPublicKeyInfoPem());
		Console.WriteLine("2 " + aww.ExportPkcs8PrivateKeyPem());//error on some machines windows 10/11 but works on https://dotnetfiddle.net/
		Console.WriteLine("Sucesso");
	}
}

Expected behavior

When calling the method "keyw3.ExportPkcs8PrivateKeyPem()" the error "System.Security.Cryptography.CryptographicException HResult=0x80090029 Message=The requested operation is not supported....."

Actual behavior

not necessary, run the example

Regression?

No response

Known Workarounds

I am saving the private key to another file and rebuilding later

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions