LetsDevOps: PowerShell to Encrypt and Decrypt Password/Secret using Certificate



In Automation world we need to use password/secret in the script for authentication like connecting to Azure, Providing the Access to Azure Resources. Using the password/secret in the Script makes it risky, hence this blog will help to encrypt the password using Windows built-in tool.


Introduction


To achieve this task we need to use the certificate which we can create on the system where we want to encrypt and decrypt the password.


With this encryption it will use public key to encrypt the password but only user and system will be able to decrypt since it has the private Key associated. In this case if someone else gets the public key they will not be able to decrypt it. Hence it is powerful and safe.


Encryption


Step 1:


Creating a Certificate with New-SelfSignedCertificate. This step you need to run on the machine from where you want to encrypt and decrypt the password/secret.


New-SelfSignedCertificate -DnsName certtoencryptdecrypt -CertStoreLocation "Cert:\CurrentUser\My" -KeyUsage KeyEncipherment,DataEncipherment, KeyAgreement -Type DocumentEncryptionCert

Step 2:


Once certificate created we can use the certificate name to encrypt the password. Make sure you are running PowerShell 5.0 and Above.


"mysecretvalue" | Protect-CmsMessage -To cn=certtoencryptdecrypt -OutFile C:\Temp\encryptedsecret.txt

Here we are encrypting the password/secret "mysecretvalue" and after successful run the encrypted password will be stored at C:\Temp\encryptedsecret.txt




Decryption

Now we learn how we can decrypt the encrypted data. While decrypting we have to make sure we are using the same system and user which we used to encrypt the password/Data.


Unprotect-CmsMessage -Path C:\temp\encryptedsecret.txt


Appendix


You might get below error during the encryption and this could be due to multiple self signed certificate exist on the same system.

Error:


Solution: Run Below command to delete the certificate with the certificate name certtoencryptdecrypt.


dir cert: -Recurse | Where-Object { $_.Subject -like "*certtoencryptdecrypt*" } | Remove-Item