I've created a self-signed SSL certificate using openssl. When I import the certificate using the .NET APIs, I can't bind it to my website with netsh. I'm importing the certificate with PowerShell:
$Certificate = New-Object 'security.Cryptography.X509Certificates.X509Certificate2' $PathToCertificate
$keyFlags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet
$keyFlags = $keyFlags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet
$keyFlags = $keyFlags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable
$store = New-Object 'Security.Cryptography.X509Certificates.X509Store' 'My','LocalComputer'
$store.Open( 'ReadWrite' )
$store.Remove( $Certificate )
$store.Add( $Certificate )
$store.Close()
I then use netsh
to bind to the certificate:
netsh http add sslcert ipport=0.0.0.0:443 certhash=<thumbprint> appid=<app ID>
Which succeeds the first time run, but fails on subsequent attempt with this error:
SSL Certificate add failed, Error: 1312
A specified logon session does not exist. It may already have been terminated.
However, when I import the certificate manually through the Certificates MMC/snap-in, I never have any problems running the netsh
command.
I'm seeing this error on some of our Windows 7 and Windows 2012 R2 computers. Strangely, more than half our computers don't have this problem. Am I adding the cert incorrectly? Could I have generated a bad certificate?
I lied. Looks like I thought I was setting the key storage flags in the code above. Turns out I was loading the certificate in a different part of our script, and it wasn't specifying the correct key storage flags. After correcting my script so it actually does what I claimed it did, everything works.