Private/ConvertFrom-SecurePasscode.ps1
<#
.SYNOPSIS Decrypts a base64-encoded secure passcode back to the original plain text password. .DESCRIPTION The ConvertFrom-SecurePasscode function decrypts a previously encrypted passcode (produced by ConvertTo-SecurePasscode) using AES (CBC mode). The decryption uses the same key and initialization vector (IV) derived from the provided username to return the original plain text password. .PARAMETER Passcode The base64-encoded encrypted password string that needs to be decrypted. .PARAMETER Username The username used during encryption. It must match exactly to derive the same decryption key and IV. .EXAMPLE $plainPassword = ConvertFrom-SecurePasscode -Passcode $securePasscode -Username "service-account@test.com" Decrypts the provided base64 passcode using the given username and returns the original password. .OUTPUTS [string] The decrypted plain text password. .NOTES - This function must use the same username used during encryption with ConvertTo-SecurePasscode. - Make sure to keep usernames consistent and secret passcodes safe. #> function ConvertFrom-SecurePasscode { param ( [Parameter(Mandatory)] [string]$Passcode, [Parameter(Mandatory)] [string]$Username ) # Derive key from username only $key = [System.Text.Encoding]::UTF8.GetBytes($Username.PadRight(32, '0').Substring(0, 32)) $iv = $key[0..15] $aes = [System.Security.Cryptography.Aes]::Create() $aes.Mode = 'CBC' $aes.Key = $key $aes.IV = $iv $decryptor = $aes.CreateDecryptor() $encryptedBytes = [Convert]::FromBase64String($Passcode) $decrypted = $decryptor.TransformFinalBlock($encryptedBytes, 0, $encryptedBytes.Length) [System.Text.Encoding]::UTF8.GetString($decrypted) } |