Skip to content

Instantly share code, notes, and snippets.

@duffney
Created February 27, 2017 13:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save duffney/d78b3d9beebcf31aa053256e802ad34f to your computer and use it in GitHub Desktop.
Save duffney/d78b3d9beebcf31aa053256e802ad34f to your computer and use it in GitHub Desktop.
function New-DomainSignedCertificate {
[CmdletBinding()]
param(
[parameter(Mandatory=$true)]
[string]
$Hostname,
[parameter(Mandatory=$true)]
[string]
$Organization,
[parameter(Mandatory=$true)]
[string]
$OrganizationalUnit,
[parameter(Mandatory=$true)]
[string]
$Locality,
[parameter(Mandatory=$true)]
[string]
$State,
[parameter(Mandatory=$true)]
[string]
$Country,
[parameter(Mandatory=$true)]
[string]
$CertificateAuthority,
[parameter(Mandatory=$false)]
[string]
$Keylength = "2048",
[string]
$workdir = $env:Temp
)
$fileBaseName = $Hostname -replace "\.", "_"
$fileBaseName = $fileBaseName -replace "\*", ""
$infFile = $workdir + "\" + $fileBaseName + ".inf"
$requestFile = $workdir + "\" + $fileBaseName + ".req"
$CertFileOut = $workdir + "\" + $fileBaseName + ".cer"
Try {
Write-Verbose "Creating the certificate request information file ..."
$inf = @"
[Version]
Signature="`$Windows NT`$"
[NewRequest]
Subject = "CN=$Hostname, OU=$OrganizationalUnit, O=$Organization, L=$Locality, S=$State, C=$Country"
KeySpec = 1
KeyLength = $Keylength
Exportable = TRUE
FriendlyName = "$Hostname"
MachineKeySet = TRUE
SMIME = False
PrivateKeyArchive = FALSE
UserProtected = FALSE
UseExistingKeySet = FALSE
ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
ProviderType = 12
RequestType = PKCS10
KeyUsage = 0xa0
"@
$inf | Set-Content -Path $infFile
Write-Verbose "Creating the certificate request ..."
& certreq.exe -new "$infFile" "$requestFile"
Write-Verbose "Submitting the certificate request to the certificate authority ..."
& certreq.exe -submit -config "$CertificateAuthority" -attrib "CertificateTemplate:WebServer" "$requestFile" "$CertFileOut"
if (Test-Path "$CertFileOut") {
Write-Verbose "Installing the generated certificate ..."
& certreq.exe -accept "$CertFileOut"
}
}
Finally {
Get-ChildItem "$workdir\$fileBaseName.*" | remove-item
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment