Importing self-signed certificate throws NTE_NOT_SUPPORTED

80 Views Asked by At

I'm creating a self-signed certificate via powershell as follows

$file='c:\temp\testcert.pfx'
$email = "[email protected]"
$mailname = "testmail"

$pwd = "tst"
$dnsname="friends.com"
$password = (convertto-securestring -string $pwd -force -asplaintext)
$params = @{
    Subject = "E=$email,CN=$mailname"
    KeyAlgorithm = 'RSA'
    KeyLength = 2048
    CertStoreLocation = 'Cert:\CurrentUser\My'
    NotAfter = (Get-Date).AddYears(1)
    NotBefore = (Get-Date).AddYears(-1)
    KeyUsage = @("DigitalSignature","CRLSign","CertSign","KeyEncipherment")
    DnsName = $dnsname
}
$cert = New-SelfSignedCertificate @params
Export-PfxCertificate -cert "Cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath $file -Password $password
$pwd | certutil -dump $file

Using this I want to first import it, then add it to TemporarySecureMimeContext.

    var certFilePath = "c:\\temp\\testcert.pfx";
    var secureCtx = new TemporarySecureMimeContext();
    var cert = new X509Certificate2(certFilePath , "tst", X509KeyStorageFlags.Exportable);
    secureCtx.Import(cert);

At this point, I get NTE_NOT_SUPPORTED from System.Security.Cryptography.CngKey.Export bubbling all the way up.

Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException : The requested operation is not supported.
   at System.Security.Cryptography.CngKey.Export(CngKeyBlobFormat format)
   at System.Security.Cryptography.RSACng.ExportKeyBlob(Boolean includePrivateParameters)
   at System.Security.Cryptography.RSACng.ExportParameters(Boolean includePrivateParameters)
   at MimeKit.Cryptography.AsymmetricAlgorithmExtensions.GetAsymmetricKeyParameters(RSA rsa, Boolean publicOnly, AsymmetricKeyParameter& pub, AsymmetricKeyParameter& key)
   at MimeKit.Cryptography.AsymmetricAlgorithmExtensions.GetAsymmetricKeyParameter(RSA rsa)
   at MimeKit.Cryptography.AsymmetricAlgorithmExtensions.AsAsymmetricKeyParameter(AsymmetricAlgorithm key)
   at MimeKit.Cryptography.X509Certificate2Extensions.GetPrivateKeyAsAsymmetricKeyParameter(X509Certificate2 certificate)
   at MimeKit.Cryptography.TemporarySecureMimeContext.Import(X509Certificate2 certificate, CancellationToken cancellationToken)

Certificate gets imported successfully if I do secureCtx.Import(certFilePath, "tst");.

Can anyone share insight on what is the issue here and/or share the working code I can refer to?

1

There are 1 best solutions below

0
On

The TemporarySecureMimeContext.Load(string fileName, string passwd) method works because it doesn't use the X509Certificate2 API, it uses the BouncyCastle Pkcs12 API to load the pfx file.

Since MimeKit is Open Source, you can just check out how I do it here: https://github.com/jstedfast/MimeKit/blob/master/MimeKit/Cryptography/TemporarySecureMimeContext.cs#L416-L446