In case you cannot use the CredentialManager PowerShell module to store and retrieve user credentials, but you still need to securely store user passwords or other confidential data there is another way to do so.
1. Securely Encrypt and Store a string
Our task: securely store the password " SuperS3cretPasswd!!!" for the user Admin so it can be used in scripts.
PowerShell can utilize DPAPI (Data Protection application programming interface) to take a secure string, then encrypt and store it in a plain text file in the file system.
ConvertTo-SecureString -String "SuperS3cretPasswd!!!" -Force -AsPlainText | ConvertFrom-SecureString | Set-Content c:\temp\pass.txt
This command will generate pass.txt with the following content:
01000000d08c9ddf0115d1118c7a00c04fc297eb0100000048e7e3749498ba4c9853e9009c2ac55c00000000020000000000106600000001000020000000f6ea725e432d94bc64522a15445f1360af3262bd97b8e20f8ca2117c3a116e81000000000e8000000002000020000000ad6eb30ea722360c84f758b417149550d26550acfa1585dc8ad666390cc9c891300000003a3759bbffbaf86ca5fbb0863366da540a0dc4b75f617af71c8f968bababc7669f892a4eee5eb4441dd67a169b363ab0400000005559cf3b7edcc815bfd6ae14f4b26ab9ca76ee5a8ba0e2c961155af880eac5f165d7d6280a6129c09c323e9a177fde0725d208a80a2e138cd126514ca7bba432
That begs the question: what if someone opens that text file, will they be able to decrypt the password just as easily like we do? The answer fortunately is no. DPAPI uses the actual user credentials from LSA to encrypt and decrypt the text file, so only the user who encrypted it can decrypt it's contents, even if others gain access to the content of the text file.
That doesn't mean however that you should not lock the file down with the appropriate NTFS permissions as an extra security measure, so it should only be readable by you.
2.1 Decrypt our stored String to build a credential object
# Decrypt the password from pass.txt $SecureStr = $(Get-Content c:\temp\pass.txt | ConvertTo-SecureString) # Build a credential object using the username and the decrypted password [PsCredential]$cred = New-Object System.Management.Automation.PSCredential ("Admin", $SecureStr) # Connect to Office365 using the stored credentials Connect-ExchangeOnline -Credential $cred
2.2 Recover the original string from pass.txt
If you need the original string recovered from the encrypted text file, use the following formula:
$Original = [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecureStr))
Comments