Skip to content

Instantly share code, notes, and snippets.

@NaibafCH
Created December 15, 2017 14:04
Show Gist options
  • Save NaibafCH/431acc78ea4078a3c86228c0eb6f7533 to your computer and use it in GitHub Desktop.
Save NaibafCH/431acc78ea4078a3c86228c0eb6f7533 to your computer and use it in GitHub Desktop.
function Invoke-NewSignedCertificateWindows81Task {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[string]$DnsName
)
Write-Host "DnsName: $DnsName"
$KeystoreFile = $DnsName + '.keystore.jks'
$KeystorePassword = 'secret'
$P12Path = [IO.Path]::ChangeExtension($KeystoreFile, 'p12')
if((Test-Path $P12Path)) {
Write-Host "Removing $P12Path..."
Remove-Item $P12Path
}
try {
$keytool = (Get-Command 'keytool.exe').Source
} catch {
$keytool = Read-Host "keytool.exe not on path. Enter path to keytool (found in JRE bin folder)"
if([string]::IsNullOrEmpty($keytool) -or -not (Test-Path $keytool)) {
Write-Error "Keytool path was invalid."
}
}
Write-Host ''
Write-Host 'Generating JKS keystore...'
& $keytool -genkeypair -alias $DnsName -keyalg RSA -keysize 2048 -keypass $KeystorePassword -storepass $KeystorePassword -validity 9999 -keystore $KeystoreFile -ext SAN=DNS:$DnsName,IP:127.0.0.1 -dname "CN=$DnsName, OU=Organizational Unit, O=Organization, L=Location, ST=State, C=Country"
Write-Host ''
Write-Host 'Generating .p12 to import to Windows...'
& $keytool -importkeystore -srckeystore $KeystoreFile -destkeystore $P12Path -srcstoretype jks -deststoretype pkcs12 -srcstorepass $KeystorePassword -deststorepass $KeystorePassword
Write-Host ''
Write-Host 'Trusting generated SSL certificate...'
$secureStringKeystorePassword = ConvertTo-SecureString -String $KeystorePassword -Force -AsPlainText
$fullpath = Resolve-Path $P12Path
$keyStorageFlags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable -bxor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet -bxor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet;
$certificate = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ErrorAction Stop;
$certificate.Import($fullpath, $secureStringKeystorePassword, $keyStorageFlags);
$store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList My, LocalMachine -ErrorAction Stop;
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite);
$store.Add($certificate);
$store.Close();
$certificate = Import-PfxCertificate -FilePath $P12Path -Password $secureStringKeystorePassword -CertStoreLocation Cert:\LocalMachine\Root
Write-Host 'SSL certificate is now locally trusted. (added as root CA)'
}
Register-SitecoreInstallExtension -Command Invoke-NewSignedCertificateWindows81Task -As NewSignedCertificateWindows81 -Type Task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment