Created
January 21, 2020 19:17
-
-
Save andreasbotsikas/afebac994ba9ae5c7bd1093473a7464e to your computer and use it in GitHub Desktop.
Generate pfx and snk file to sign an SQL CLR assembly
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
$solutionName="SampleDll" | |
$pfxPassword="password" | |
$pvkFilePath="$PSScriptRoot\$($solutionName)Key.pvk" | |
$cerFilePath="$PSScriptRoot\$($solutionName)Key.cer" | |
$pfxFilePath="$PSScriptRoot\$($solutionName)Key.pfx" | |
$snkFilePath="$PSScriptRoot\$($solutionName)Key.snk" | |
if (![System.IO.File]::Exists($pfxFilePath)){ | |
# Generate private key and public cer file. | |
# -n ➜ Subject’s certificate name | |
# -len ➜ The generated key length in bits | |
# -a ➜ We declare which signature algorithm we will be using | |
# -r ➜ Indicates that this certificate is self signed | |
# -e ➜ Expiration date | |
makecert -n "CN=$solutionName" -len 2048 -r -a sha512 -e 01/01/2200 -sv $pvkFilePath $cerFilePath | |
# A popup will appear asking for pvk password. Just hit Ok and Yes to confirm no password. | |
# The pvk file is deleted after the pfx file is generated. | |
# Add Windows SDK Kit in path to be able to call pvk2pfx | |
$Env:Path += ";C:\Program Files (x86)\Windows Kits\10\bin\x64\" | |
pvk2pfx -pvk $pvkFilePath -spc $cerFilePath -po $pfxPassword -pfx $pfxFilePath | |
# Remove unsecure pvk file | |
del $pvkFilePath | |
}else{ | |
Write-Host "Skipping generation of $pfxFilePath since it exists!" | |
} | |
# The following code generates the snk file from the pfx file | |
# Read in the bytes of the pfx file | |
[byte[]] $pfxBytes = Get-Content $pfxFilePath -Encoding Byte; | |
# Get a cert object from the pfx bytes with the private key marked as exportable | |
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2( | |
$pfxBytes, | |
$pfxPassword, | |
[Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable); | |
# Export a CSP blob from the cert (which is the same format as an SNK file) | |
[byte[]] $snkBytes = ([Security.Cryptography.RSACryptoServiceProvider]$cert.PrivateKey).ExportCspBlob($true); | |
# Write the CSP blob/SNK bytes to the snk file | |
[IO.File]::WriteAllBytes($snkFilePath, $snkBytes); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment