Skip to content

Issue in ECDsaCertificateExtensions.CopyWithPrivateKey with TPM #75971

@Fassino

Description

@Fassino

Description

When creating a Cng ECDSA private key in the TPM Cng and using CertificateRequest to generate a self signed certificate.

The implementation calls ECDsaCertificateExtensions.CopyWithPrivateKey which call Helpers.AreSamePublicECParameters(publicKey.ExportParameters(false), privateKey.ExportParameters(false))).
Unfortunately privateKey.ExportParameters returns a structure where the ECParameters.Curve.Oid.Value is not set.
That breaks AreSamePublicECParameters which returns false and raise an exception in CopyWithPrivateKey.

System.ArgumentException: The provided key does not match the public key for this certificate. (Parameter 'privateKey')
at System.Security.Cryptography.X509Certificates.ECDsaCertificateExtensions.CopyWithPrivateKey(X509Certificate2 certificate, ECDsa privateKey)
at System.Security.Cryptography.X509Certificates.CertificateRequest.CreateSelfSigned(DateTimeOffset notBefore, DateTimeOffset notAfter)

Reproduction Steps

        CngKeyCreationParameters keyParams = new()
        {
            Provider = new CngProvider("Microsoft Platform Crypto Provider"),
        };
        CngKey key = CngKey.Create(CngAlgorithm.ECDsaP384, "KeyInTPM", keyParams);
        ECDsaCng cngkey = new ECDsaCng(key);
        CertificateRequest request = new(
                subjectName,
                cngkey ,
                HashAlgorithmName.SHA256);
        X509Certificate2 selfSigned = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow);

Expected behavior

No exception.

Actual behavior

Exception

Regression?

No response

Known Workarounds

No know workaround

Configuration

Bug occurs on:
Windows 10 Pro wich Visual Studio 2022 and .net 5.0.
Windows 10 Pro wich Visual Studio 2022 and .net 6.0.

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions