Powershell: Encrypting strings using [Protect|Unprotect]-CmsMessage

There are cases we want to encrypt strings, such as passwords or

PowerShell has come a long way, and it supports IETF standard RFD5652 cryptography method using certificate.
Note below methods support starting PowerShell version 5.0

Create inf file to generate certificate:

Signature = "$Windows NT$"

Subject = "cn=newcertificate@contoso.com"
MachineKeySet = false
KeyLength = 2048
HashAlgorithm = Sha1
Exportable = true
RequestType = Cert
ValidityPeriod = "Years"
ValidityPeriodUnits = "100"


We’ll call it automation.inf and will use below command to generate and add new certificate to current user
certreq -new automation.inf automation.cer

It will look something like this:
PS C:\ > certreq -new .\automation.inf c:\scrap\automation.cer
Installed Certificate:
Serial Number: 50a625ea82fd1b6d44ccc85f441e0604
Subject: CN=newcertificate@contoso.com
Thumbprint: 1813dc1407560652482f87bae69cf40bd5953d68
Microsoft Strong Cryptographic Provider

This will create certificate to desired location, it will also automatically add to current user person certificate store. You can use below command to list recently created/imported certificate:
Get-ChildItem Cert:\CurrentUser\My\ -DocumentEncryptionCert

In case if you like to use different server, and would like to import the public certificate to other server, use below command
Import-Certificate -FilePath .\auditautomation.cer -CertStoreLocation cert:\CurrentUser\My

* There are ways to export private keys to other server. Keep in mind when exporting private key, you need to aware you could potentially risking unprotecting the sensitive private key! It is important to understand you should uncheck “Mark this key as exportable” on other servers:

To encrypt the string, use below commands:
$a = 'ThisIsString123!'
$msg = Protect-CmsMessage -Content $a -to .\auditautomation*

To decrypt the string, use below commands
Unprotect-CmsMessage -Content $msg -To Cert:\CurrentUser\My\auditautomation*

If the certificate is imported to local machine:
Unprotect-CmsMessage -Content $msg -To Cert:\LocalMachine\My\auditautomation*

Reference Link:
PowerShell V5 New Feature: Protect/Unprotect-CmsMessage