You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
2.0 KiB

  1. Param(
  2. [parameter(Mandatory=$true)][string]$vaultName,
  3. [parameter(Mandatory=$true)][string]$certName,
  4. [parameter(Mandatory=$true)][string]$certPwd,
  5. [parameter(Mandatory=$true)][string]$subjectName,
  6. [parameter(Mandatory=$false)][string]$ValidityInMonths=12,
  7. [parameter(Mandatory=$true)][string]$saveDir
  8. )
  9. #Log in Azure Account
  10. Login-AzureRmAccount
  11. # Create Cert in KeyVault
  12. Write-Host "Creating certificate in Azure KeyVault..." -ForegroundColor Yellow
  13. $policy = New-AzureKeyVaultCertificatePolicy -SubjectName $subjectName -IssuerName Self -ValidityInMonths $ValidityInMonths
  14. Add-AzureKeyVaultCertificate -VaultName $vaultName -Name $certName -CertificatePolicy $policy
  15. # Downloading Certificate
  16. Write-Host "Downloading Certificate from KeyVault..." -ForegroundColor Yellow
  17. $Stoploop = $false
  18. $Retrycount = 0
  19. do {
  20. try {
  21. $kvSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certName -ErrorAction SilentlyContinue
  22. $kvSecretBytes = [System.Convert]::FromBase64String($kvSecret.SecretValueText)
  23. $certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
  24. $certCollection.Import($kvSecretBytes,$null,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
  25. $protectedCertificateBytes = $certCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $certPwd)
  26. [System.IO.File]::WriteAllBytes($saveDir + "\" + $certName + ".pfx", $protectedCertificateBytes)
  27. $Stoploop = $true
  28. Write-Host "Finished!" -ForegroundColor Yellow
  29. }
  30. catch {
  31. if ($Retrycount -gt 5){
  32. $Stoploop = $true
  33. Write-Host "Not possible to retrieve the certificate!" -ForegroundColor Yellow
  34. }
  35. else {
  36. Start-Sleep -Seconds 20
  37. $Retrycount = $Retrycount + 1
  38. }
  39. }
  40. }
  41. While ($Stoploop -eq $false)
  42. # Show Certificate Values
  43. Get-AzureKeyVaultCertificate -VaultName $vaultName -Name $certName