Storing Credentials securely

Hi together,

I have been asked many times how to store and use securely credentials / passwords in scripts. The simplest thing is just to create a credential on a computer and export it via Export-Clixml where you make use of the SecureString and the native Windows Data Protection API (DAPI), which is secure. (take a look here) But the downside is that you can decrypt the securestring only at the computer and with the user who encrypted it.

Therefore I want to show you this simple but neat way to achieve this task on all computers. For this we simply make use of certificates to encrypt and decrypt the passwords which you would preferably create with your own PKI and deploy with your management solution.

How does this look like? As simple as this:

Install-Module ProtectedData

#Testing purpose
New-SelfSignedCertificate -Subject PowershellSec -KeyUsage KeyEncipherment -CertStoreLocation Cert:\CurrentUser\My 

#Retrieving cert
$Cert = Get-ChildItem Cert:\CurrentUser\My | Where-Object {$_.Subject -like '*PowershellSec*'}

#Production
#$Cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -like 'CN=PowerShell Automation*'}

# Encrypt password and store it in a file.
Protect-Data 'Password' -Certificate $Cert | Export-Clixml .\encrypted.xml

# Decrypt password from file within script.
$PasswordToUse = Unprotect-Data (Import-Clixml .\encrypted.xml) -Certificate $Cert 

$PasswordToUse

Alternatively you could also just use the Powershell built-in cmdlets:
Protect-CmsMessage and Unprotect-CmsMessage

Happy using!

David

Advertisement