Powershell masking password

Hello Everyone,

I have the script (API POST) below which is working fine.

$UserPass = “username:password”

[string]$stringToEncode=$UserPass

$encodedString=[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($stringToEncode))

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$headers = New-Object “System.Collections.Generic.Dictionary[[String],[String]]”

$headers.Add(“content-type”, “application/json”)

$headers.Add(“accept”, “application/json”)

$headers.Add(“Authorization”, "Basic " + $encodedString)

Invoke-RestMethod -Uri “https://api_base_url/session” -Headers $headers -Method POST

I want to mask the password instead of plain text. So modified it to below which will ask to enter the masked password.

$UserPass = “username:$(Read-Host -Prompt “Please type the password” -AsSecureString)”

But the whole script is not working anymore. When I troubleshoot, there is a difference in encoding/decoding. I ran an online base64 decode and encode, the result is different.

Plain text password - username:password
dXNlcm5hbWU6cGFzc3dvcmQ= —> username:password

Masked password - username:$(Read-Host -Prompt “Please type the password” -AsSecureString)
dXNlcm5hbWU6U3lzdGVtLlNlY3VyaXR5LlNlY3VyZVN0cmluZw== —> username:System.Security.SecureString

How can I mask the password but able to read the System.Security.SecureString as the actual password?

Thank you in advanced.

Hello, please edit your post and use the preformatted text button to format your code blocks so that they are easier to read.

First a couple of clarifications; encoding does not equal encryption. Is your end goal to have the user supply the password at script execution?

I also suggest reading some of the Microsoft documentation about SecureStrings. By passing the AsSecureString parameter to Read-Host you’re having it convert the plaintext input into a SecureString object. If you want to decrypt that SecureString object back into a plaintext string you’ll have to add a bit of extra code using some .NET methods.

I recommend always storing credentials in a PowerShell credential object.

It provides a secure method for getting credentials from user input, and it’s easy in code to pull the username and password out of the object.

$Credential = Get-Credential
$UserID = $Credential.GetNetworkCredential().UserName
$Password = $Credential.GetNetworkCredential().password

If this is an automation process, where the credential needs to be stored, I suggest using the SecretsManagement module to store the credential object for retrieval by the script.

2 Likes
$Pwd = Read-Host -AsSecureString -Prompt 'Enter the Password'
$PassWord = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd))
1 Like