Request, Export and Import Certificate Using PowerShell


 

Hi,

I am targeting to create a personal certificate in this blog post, configure the certificate, export it in local machine and then import it in another remote machine.

1. Request new Certificate

   1: Set-Location 'Cert:\LocalMachine\My'
   2: $cert = Get-Certificate -Template Machine -Url ldap:///CN=contoso-PKI-CA -DnsName MyVM01.contoso.com -CertStoreLocation Cert:\LocalMachine\My
   3: $thumbprint = $cert.Certificate.Thumbprint

2. Manage Private Keys

   1: #manage private keys
   2: $cert = Get-ChildItem -Recurse "Cert:\LocalMachine\My\$thumbprint"
   3: $stub = "\Microsoft\Crypto\RSA\MachineKeys\"
   4: $programData = $Env:ProgramData
   5: $keypath = $programData + $stub
   6: $certHash = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
   7: $certFullPath = $keypath + $certHash
   8: $certAcl = Get-Acl -Path $certFullPath
   9: $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule 'contoso\cloud_pack_setup', 'ReadData,FullControl', 'Allow'
  10: $certAcl.AddAccessRule($accessRule)
  11: Set-Acl $certFullPath $certAcl

3. Copy Certificate from one store to another store

   1: #Copy certificate from personal to intermediate certification authorities
   2: Export-Certificate -Type CERT -FilePath C:\OrchCert.cer -Cert "Cert:\LocalMachine\My\$thumbprint"
   3: Import-Certificate -CertStoreLocation Cert:\LocalMachine\CA -FilePath C:\OrchCert.cer

4. Export Certificate

   1: #export certificate (Orch)
   2: Export-Certificate -Type CERT -FilePath C:\OrchCert.cer -Cert "Cert:\LocalMachine\CA\$thumbprint"

5. Copy Certificate from local machine to remote Machine

   1: #copy certificate from Orch VM to Portal VM
   2: Set-Location C:\Windows\System32
   3: Copy-Item C:\OrchCert.cer -Destination \\CPPortal01\C$\OrchCert.cer -Force

6. Import Certificate in remote machine after it is copied

   1: #import certificate in portal vm (asp portal)
   2: Import-Certificate -CertStoreLocation Cert:\LocalMachine\CA -FilePath C:\OrchCert.cer

The above steps can be merged to create a whole PowerShell script that creates , exports and imports a certificate.


Comments (3)

  1. M0dest0 says:

    Hi, you think that is possible to edit Validity for an existing CA TEmplate using Powershell or c#? Thanks.

  2. Curtiss says:

    ldap:///CN=contoso-PKI-CA

    is "contoso-PKI-CA" just the name of the CA, or do I need to find that somewhere in adsiedit?

  3. Brain2000 says:

    Requesting the machine certificate with Powershell can be done in one command:

    PS C:> Get-Certificate -Template Machine -CertStoreLocation cert:LocalMachineMy