Search code examples
powershellautomationrsax509certificatex509certificate2

GetRSAPrivateKey UniqueName returns empty string


I am generating self signed certifcate using powershell script and importing it to the certificate store. Now I need to assign a new user in manage private keys section for the certificate.

I was trying the following code sample to do so.

$certificate = (import the certificate)

## Identify the user you'll be granting permission to
$grantee_name = 'dev\Batman'
$grantee = New-Object System.Security.Principal.NTAccount($grantee_name)

## Get the location and permission-of the cert's private key
$privatekey_rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
$privatekey_file_name = $privatekey_rsa.key.UniqueName
$privatekey_path = "${env:ALLUSERSPROFILE}\Microsoft\Crypto\Keys\${privatekey_file_name}"
$privatekey_file_permissions = Get-Acl -Path $privatekey_path

## Grant the user 'read' access to the key
$access_rule = New-Object System.Security.AccessControl.FileSystemAccessRule($grantee, 'Read', 'None', 'None', 'Allow')
$privatekey_file_permissions.AddAccessRule($access_rule)
Set-Acl -Path $privatekey_path -AclObject $privatekey_file_permissions

In my case

$privatekey_file_name = $privatekey_rsa.key.UniqueName 

returns empty string. Attaching screenshot as well.

Powershell image


Solution

  • When you specify -path and -password parameters, private key is not persisted and the certificate is not installed. In order to install the certificate, you need to remove mentioned parameters and use -StoreLocation parameter to indicate in which store the certificate must be installed.