Private/ConvertTo-SecurePasscode.ps1

<#
.SYNOPSIS
Encrypts a plaintext password into a secure base64 passcode using AES encryption.
 
.DESCRIPTION
The ConvertTo-SecurePasscode function encrypts a plain text password using AES (CBC mode) based on a derived key from the provided username.
This encrypted passcode can then be stored securely and later decrypted using the corresponding ConvertFrom-SecurePasscode function.
 
.PARAMETER Password
The plain text password that needs to be encrypted.
 
.PARAMETER Username
The username used to derive the encryption key and initialization vector. It must be consistent when decrypting.
 
.EXAMPLE
$securePasscode = ConvertTo-SecurePasscode -Password "MyP@ssw0rd123" -Username "service-account@test.com"
 
Encrypts the password "MyP@ssw0rd123" using the username and returns a base64-encoded passcode.
 
.OUTPUTS
[string]
A base64 string representing the encrypted password.
 
.NOTES
- The derived encryption key is based on the padded username.
- Use ConvertFrom-SecurePasscode to decrypt the resulting passcode.
- Ensure both username and key derivation logic remain consistent between encryption and decryption.
#>


function ConvertTo-SecurePasscode {
    param (
        [Parameter(Mandatory)]
        [string]$Password,

        [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

    $encryptor = $aes.CreateEncryptor()
    $passwordBytes = [System.Text.Encoding]::UTF8.GetBytes($Password)
    $encrypted = $encryptor.TransformFinalBlock($passwordBytes, 0, $passwordBytes.Length)
    [Convert]::ToBase64String($encrypted)
}