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

Advertisements

One thought on “Storing Credentials securely

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s