Created
October 2, 2014 17:28
-
-
Save BrandonLWhite/235fa12247f6dc827051 to your computer and use it in GitHub Desktop.
Import .cer and .pvk certificate files programmatically in C# for use with `netsh http add sslcert`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Security.Cryptography.X509Certificates; | |
using System.Security.Cryptography; | |
var abyPublicKey = AssemblyUtility.GetEmbeddedFileAsByteArray("WebServer.SslCertificate.cer"); | |
var abyPrivateKey = AssemblyUtility.GetEmbeddedFileAsByteArray("WebServer.SslCertificate.pvk"); | |
var certificate = new X509Certificate2(abyPublicKey, string.Empty, | |
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); | |
var cspParams = new CspParameters | |
{ | |
ProviderType = 1, | |
Flags = CspProviderFlags.UseMachineKeyStore, | |
KeyContainerName = Guid.NewGuid().ToString().ToUpperInvariant() | |
}; | |
var rsa = new RSACryptoServiceProvider(cspParams); | |
rsa.ImportCspBlob(ExtractPrivateKeyBlobFromPvk(abyPrivateKey)); | |
rsa.PersistKeyInCsp = true; | |
certificate.PrivateKey = rsa; | |
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); | |
store.Open(OpenFlags.ReadWrite); | |
store.Add(certificate); | |
store.Close(); | |
string sCertHash = certificate.GetCertHashString(); | |
var guid = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), true).FirstOrDefault() as System.Runtime.InteropServices.GuidAttribute; | |
string sNetShArgs = string.Format("http add sslcert ipport=0.0.0.0:8080 certhash={0} appid={1}", | |
sCertHash, '{' + guid.Value + '}'); | |
System.Diagnostics.Process.Start("netsh", sNetShArgs).WaitForExit(); |
What is
ExtractPrivateKeyBlobFromPvk
?
According to ImportCspBlob(), it's a method to convert abyPrvivatekey to byte[].
What is ExtractPrivateKeyBlobFromPvk?
It's a Byte()
that's exported from an RSACryptoServiceProvider
instance.
FYI I've posted a working example here: https://stackoverflow.com/a/78463389
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is
ExtractPrivateKeyBlobFromPvk
?