Store and retreive RSA private key in Windows

779 views Asked by At

I have a pretty simple scenario/requirement:

  1. Generate RSA private/public key pair through OpenSSL or any online RSA key pair generator
  2. Save the private key to the windows internal store (so it does not lay around as just a file somewhere
  3. Create a PowerShell script, that looks into the store, locates the key, and uses it. (basically, I will have a PS script, to which I send a 3rd party tool already encrypted password, and I expect that PS script to decrypt that password using a locally stored private key and use it on-the-fly)

This so far showed an unreachable goal, because:

  • I haven't found a way, how to import .pem file with the key
  • .cer file apparently does not contain the key
  • the only way (so far what I have found) how to import the key is conversion to .pfx file, which can be imported, BUT
  • .pfx file cannot be read as plain text - there seems to be no reasonable way from Powershell to locate the key and read it for usage in decryption
  • there is a module PSPKI, but it seems to accept the file and not the stored/installed certificate/key.

So anyone has any idea, how can I import a simple private key to Windows for later read-out from PowerShell for further usage?

Thank you!

1

There are 1 answers

1
Daniel Fisher  lennybacon On

Have a look at this class to load the PFX: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2?view=net-7.0

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("c:\my.pfx", "password");

Next step is to open the store. After you checked which one fits best (machine or user) you can use X509Store to read and write there. Do not forget the Open method. When a certificate with private key (off) is added the key ist stored and the file can be deleted.