ProtectStrings.psm1
### --- PUBLIC FUNCTIONS --- ### #Region - Export-MasterPassword.ps1 Function Export-MasterPassword { <# .Synopsis Export the currently set Master Password to a text file .Description Function to retrieve the currently set master password and export it to a text file for transportation between systems or backup. Similar in end result to generating an AES key and saving it to file. .Parameter FilePath Destination full path (including file name) for exported AES Key. .EXAMPLE PS C:\> Export-MasterPassword -FilePath C:\temp\keyfile.txt this will convert the current session AES key from a SecureString object to its raw byte values, encode in Base64 and export it to a file called keyfile.txt .NOTES Version: 1.0 Author: C. Bodett Creation Date: 3/28/2022 Purpose/Change: Initial function development #> [cmdletbinding()] Param ( [Parameter(Mandatory = $true, Position = 0)] [validatescript({ if( -not ($_.DirectoryName | test-path) ){ throw "Folder does not exist" } return $true })] [Alias('Path')] [System.IO.FileInfo]$FilePath ) Begin { $SecureAESKey = Try { $Global:AESMP } Catch { # do nothing } } Process { if ($SecureAESKey) { Write-Verbose "Stored AES key found" $ClearTextAESKey = ConvertFrom-SecureStringToPlainText $SecureAESKey Write-Verbose "Converting to Base64 before export" $EncodedKey = ConvertTo-Base64 -TextString $ClearTextAESKey Write-Verbose "Saving to $Filepath with Encoded key:" Out-File -FilePath $FilePath -InputObject $EncodedKey -Force } else { Write-Warning "No key found to export" } } } #Region - Get-AESKeyConfig.ps1 Function Get-AESKeyConfig { <# .Synopsis Function to retrieve settings for use with PBKDF2 to create an AES Key .NOTES Version: 3.0 Author: C. Bodett Creation Date: 4/12/2024 Purpose/Change: Overhaul for storing defaults in function, and retrieving custom settings from ENV variable #> [cmdletbinding()] Param ( # No Parameters ) if ($EnvConfig = [System.Environment]::GetEnvironmentVariable("ProtectStrings","User")) { try { $Settings = $EnvConfig | ConvertFrom-Json -ErrorAction Stop } catch { throw $_ } } else { # Default settings $Settings = @{ Salt = 'fMK9w4HDtMO4d8Oa4pmAw6U+fknCqWvil4Q9w73DscOtw64=' Iterations = 600000 Hash = 'SHA256' } } $Settings } #Region - Get-MasterPassword.ps1 Function Get-MasterPassword { <# .Synopsis Returns the saved MasterPassword derived key. .Description This function is mostly used to verify that a MasterPassword is currently stored. It returns a SecureString object with the current stored AES key. .EXAMPLE PS C:\> Get-MasterPassword does stuff .NOTES Version: 1.0 Author: C. Bodett Creation Date: 3/28/2022 Purpose/Change: Initial function development #> [cmdletbinding()] Param ( [Switch]$Boolean ) Write-Verbose "Checking for stored AES key" if ($Boolean) { Get-AESMPVariable -Boolean } else { Get-AESMPVariable } } #Region - Import-MasterPassword.ps1 Function Import-MasterPassword { <# .Synopsis Import a previously exported master password from a text file .Description Function to import a previously exported master password keyfile and save it in the current session as the master password. .Parameter FilePath Destination full path (including file name) for the file containing the exported AES Key. .EXAMPLE PS C:\> Import-MasterPassword -FilePath C:\temp\keyfile.txt This will important the key from keyfile.txt and store it in the current Powershell session as the Master Password. .NOTES Version: 1.0 Author: C. Bodett Creation Date: 3/28/2022 Purpose/Change: Initial function development #> [cmdletbinding()] Param ( [Parameter(Mandatory = $true, Position = 0)] [validatescript({ if( -not ($_ | test-path) ){ throw "File does not exist" } if(-not ( $_ | test-path -PathType Leaf) ){ throw "The -FilePath argument must be a file" } return $true })] [Alias('Path')] [System.IO.FileInfo]$FilePath ) Begin { Try { Write-Verbose "Retreiving file content from: $FilePath" $EncodedKey = Get-Content -Path $FilePath -ErrorAction Stop } Catch { Write-Error $_ } } Process { If ($EncodedKey) { $ClearTextAESKey = ConvertFrom-Base64 -TextString $EncodedKey Write-Verbose "Storing AES Key to current session" $SecureAESKey = ConvertTo-SecureString -String $ClearTextAESKey -AsPlainText -Force Set-AESMPVariable -MPKey $SecureAESKey } } } #Region - Protect-String.ps1 Function Protect-String { <# .Synopsis Encrypt a provided string with DPAPI or AES 256-bit encryption and return the cipher text. .Description This function will encrypt provided string text with either Microsoft's DPAPI or AES 256-bit encryption. By default it will use DPAPI unless specified. Returns a string object of Base64 encoded text. .Parameter InputString This is the string text you wish to protect with encryption. Can be provided via the pipeline. .Parameter Encryption Specify either DPAPI or AES encryption. AES is the default if not specified. DPAPI is not recommended on non-Windows systems are there is no encryption for SecureStrings. .EXAMPLE PS C:\> Protect-String "Secret message" D01000000d08c9ddf0115d1118c7a00c04fc297eb010000001a8fc10bbb86cc449a5103047b4b246d0000000002000000000003660000c0000000100000003960a9bffe1fcf050567397531eb71da0000000004800000a00000001000000098435688c310d7254279e472ce2bf2b820000000eaca228aae688c9f8dc1eb304178078cbe0d54364b922d453b8899ca3b438c5a14000000848a67d2fb9c54bd64833d89387c0f4193422ff5?TE5JUEMyMjIxNTBMXEJvZGV0dEM= This command will encrypt the provided string with DPAPI encryption and return the encoded cipher text. .EXAMPLE PS C:\> Protect-String "Secret message" -Encryption AES Enter Master Password: ******** A7B3uXRDkDZkejQVQhwqn2I4KJjsxfqCbc1a+9Jgg620= This command will encrypt the provided string with AES 256-bit encryption. If no Master Password is found in the current session (set with Set-MasterPassword) then it will prompt for one to be set. .NOTES Version: 1.3 Author: C. Bodett Creation Date: 12/5/2024 Purpose/Change: Changed how output is handled to reduce length #> [cmdletbinding()] Param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [String]$InputString, [Parameter(Mandatory = $false, Position = 1)] [ValidateSet("DPAPI","AES")] [String]$Encryption = "AES" ) Begin { Write-Verbose "Encryption Type: $Encryption" If ($Encryption -eq "AES") { Write-Verbose "Retrieving Master Password key" $SecureAESKey = Get-AESMPVariable $ClearTextAESKey = ConvertFrom-SecureStringToPlainText $SecureAESKey $AESKey = Convert-HexStringToByteArray -HexString $ClearTextAESKey } If (Test-Path Variable:IsWindows) { # we know we're not running on Windows since $IsWindows was introduced in v6 If (-not($IsWindows) -and ($Encryption.ToUpper() -eq "DPAPI")) { throw "Cannot use DPAPI encryption on non-Windows host. Please use AES instead." } } } Process { Switch ($Encryption) { "DPAPI" { Try { Write-Verbose "Converting string text to a SecureString object" $ConvertedString = ConvertTo-SecureString $InputString -AsPlainText -Force | ConvertFrom-SecureString $CipherObject = New-CipherObject -Encryption "DPAPI" -CipherText $ConvertedString $CipherObject.DPAPIIdentity = Get-DPAPIIdentity Write-Verbose "DPAPI Identity: $($CipherObject.DPAPIIdentity)" #$JSONObject = ConvertTo-Json -InputObject $CipherObject -Compress #$JSONBytes = ConvertTo-Bytes -InputString $JSONObject -Encoding UTF8 #$EncodedOutput = [System.Convert]::ToBase64String($JSONBytes) #$EncodedOutput $CipherObject.ToCompressed() } Catch { Write-Error $_ } } "AES" { Try { Write-Verbose "Encrypting string text with AES 256-bit" $ConvertedString = ConvertTo-AESCipherText -InputString $InputString -Key $AESKey -ErrorAction Stop $CipherObject = New-CipherObject -Encryption "AES" -CipherText $ConvertedString #$JSONObject = ConvertTo-Json -InputObject $CipherObject -Compress #$JSONBytes = ConvertTo-Bytes -InputString $JSONObject -Encoding UTF8 #$EncodedOutput = [System.Convert]::ToBase64String($JSONBytes) #$EncodedOutput $CipherObject.ToCompressed() } Catch { Write-Error $_ } } } } } #Region - Remove-MasterPassword.ps1 Function Remove-MasterPassword { <# .Synopsis Removes the Master Password stored in the current session .Description The Master Password is stored as a Secure String object in memory for the current session. Should you wish to clear it manually you can do so with this function. .EXAMPLE PS C:\> Remove-MasterPassword This will erase the currently saved master password. .NOTES Version: 1.0 Author: C. Bodett Creation Date: 3/28/2022 Purpose/Change: Initial function development #> [cmdletbinding()] Param ( ) Write-Verbose "Removing master password from current session" Clear-AESMPVariable } #Region - Set-AESKeyConfig.ps1 Function Set-AESKeyConfig { <# .Synopsis Control the settings for use with PBKDF2 to create an AES Key .Description Allows custom configuration of the parameters associated with the PBKDF2 key generation. User can dictate the Salt, Iterations and Hash algorithm. If called with no parameters the default settings are saved to an Environment variable named ProtectStrings. .Parameter SaltString Provide a custom string to be used as the Salt bytes in PBKDF2 generation. Must be at least 16 bytes in length. .Parameter SaltBytes A byte array of at least 16 bytes can be provided for a custom salt value. .Parameter Iterations Specify the number of iterations PBKDF2 should use. 600000 is the default. .Parameter Hash Specify the Hash type used with PBKDF2. Accetable values are: 'MD5','SHA1','SHA256','SHA384','SHA512'. .Parameter Defaults Removes the Environment variable containing config. .NOTES Version: 3.0 Author: C. Bodett Creation Date: 4/12/2024 Purpose/Change: Moved parameter validation to Param Block and changed storage method from file to ENV variable #> [cmdletbinding(DefaultParameterSetName = 'none')] Param ( [Parameter(Mandatory = $false, ParameterSetName = "SaltString")] [ValidateScript({ if ([System.Text.Encoding]::UTF8.GetBytes($_).Count -lt 16) { Throw "Salt must be at least 16 bytes in length" } else { return $true } })] [String]$SaltString, [Parameter(Mandatory = $false, ParameterSetName = "SaltBytes")] [ValidateCount(16,256)] [Byte[]]$SaltBytes, [Parameter(Mandatory = $false)] [Int32]$Iterations, [Parameter(Mandatory = $false)] [ValidateSet('MD5','SHA1','SHA256','SHA384','SHA512')] [String]$Hash, [Switch]$Defaults ) $Settings = Get-AESKeyConfig if (-not($Defaults)) { Switch ($PSBoundParameters.Keys) { 'SaltString' { try { $Settings.Salt = ConvertTo-Base64 -TextString $SaltString } catch { Throw $_ } } 'SaltBytes' { try { $Settings.Salt = ConvertTo-Base64 -Bytes $SaltBytes } catch { Throw $_ } } 'Iterations' { $Settings.Iterations = $Iterations } 'Hash' { $Settings.Hash = $Hash } } $VMsg = @" `r`n Saving settings to ENV:ProtectStrings Salt........: $($Settings.Salt) Iterations..: $($Settings.Iterations) Hash........: $($Settings.Hash) "@ Write-Verbose $VMsg [Environment]::SetEnvironmentVariable("ProtectStrings", ($Settings | ConvertTo-Json -Compress), "User") } else { [System.Environment]::SetEnvironmentVariable("ProtectStrings", $null, "User") } } #Region - Set-MasterPassword.ps1 Function Set-MasterPassword { <# .Synopsis Securely retrieves from console the desired master password and saves it for the current session. .Description Takes a user provided master password as a secure string object and creates a unique AES 256 bit key from it and stores that as a SecureString object in memory for the current session. .Parameter MasterPassword If you already have a password in a variable as a SecureString object you can pass it to this function. .EXAMPLE PS C:\> Set-MasterPassword Enter Master Password: ******** In this example you will be prompted to provide a password. It will then be silently stored in the current session. .EXAMPLE PS C:\> $Pass = Read-Host -AsSecureString ***************** PS C:\> Set-MasterPassword -MasterPassword $Pass Here the desired master password is saved beforehand in the variable $Pass and then passed to the Set-MasterPassword function. .NOTES Version: 1.0 Author: C. Bodett Creation Date: 3/28/2022 Purpose/Change: Initial function development #> [cmdletbinding()] Param ( [Parameter(Mandatory = $false, Position = 0)] [SecureString]$MasterPassword ) If (-not ($MasterPassword)) { $MasterPassword = Read-Host -Prompt "Enter Master Password" -AsSecureString } Try { Write-Verbose "Generating a 256-bit AES key from provided password" $SecureAESKey = ConvertTo-AESKey $MasterPassword } Catch { throw $_ } Write-Verbose "Storing key for use within this session. Can be removed with Remove-MasterPassword" Set-AESMPVariable -MPKey $SecureAESKey } #Region - Unprotect-String.ps1 Function UnProtect-String { <# .Synopsis Decrypt a provided string using either DPAPI or AES encryption .Description This function will decode the provided protected text, and automatically determine if it was encrypted using DPAPI or AES encryption. If no master password has been set it will prompt for one. If there is a decryption problem it will notify. .Parameter InputString This is the protected text previously produced by the ProtectStrings module. Encryption type will be automatically determined. .EXAMPLE PS C:\> Protect-String "Secret message" D01000000d08c9ddf0115d1118c7a00c04fc297eb010000001a8fc10bbb86cc449a5103047b4b246d0000000002000000000003660000c0000000100000003960a9bffe1fcf050567397531eb71da0000000004800000a00000001000000098435688c310d7254279e472ce2bf2b820000000eaca228aae688c9f8dc1eb304178078cbe0d54364b922d453b8899ca3b438c5a14000000848a67d2fb9c54bd64833d89387c0f4193422ff5?TE5JUEMyMjIxNTBMXEJvZGV0dEM= This command will encrypt the provided string with DPAPI encryption and return the encoded cipher text. PS C:\> Unprotect-String 'D01000000d08c9ddf0115d1118c7a00c04fc297eb010000001a8fc10bbb86cc449a5103047b4b246d0000000002000000000003660000c0000000100000003960a9bffe1fcf050567397531eb71da0000000004800000a00000001000000098435688c310d7254279e472ce2bf2b820000000eaca228aae688c9f8dc1eb304178078cbe0d54364b922d453b8899ca3b438c5a14000000848a67d2fb9c54bd64833d89387c0f4193422ff5?TE5JUEMyMjIxNTBMXEJvZGV0dEM=' Secret message Feeding the previously output protected text to Unprotect-String will decrypt it and return the original string text. .EXAMPLE PS C:\> Protect-String "Secret message" -Encryption AES Enter Master Password: ******** A7B3uXRDkDZkejQVQhwqn2I4KJjsxfqCbc1a+9Jgg620= This command will encrypt the provided string with AES 256-bit encryption. If no Master Password is found in the current session (set with Set-MasterPassword) then it will prompt for one to be set. PS C:\> Clear-MasterPassword PS C:\> Unprotect-String 'A7B3uXRDkDZkejQVQhwqn2I4KJjsxfqCbc1a+9Jgg620=' Enter Master Password: ******** Secret message Clearing the master password from the sessino, providing the previously protected text to Unprotect-String will prompt for a master password and then decrypt the text and return the original string text. .NOTES Version: 1.4. Author: C. Bodett Creation Date: 12/5/2024 Purpose/Change: updated to handle the new output type from Protect-String #> [cmdletbinding()] Param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [String]$InputString ) Process { Write-Verbose "Converting supplied text to a Cipher Object for ProtectStrings" $CipherObject = Try { ConvertTo-CipherObject $InputString -ErrorAction Stop } Catch { Write-Warning "Supplied text could not be converted to a Cipher Object. Verify that it was produced by Protect-String." return } Write-Verbose "Encryption type: $($CipherObject.Encryption)" If ($CipherObject.Encryption -eq "AES") { $SecureAESKey = Get-AESMPVariable $ClearTextAESKey = ConvertFrom-SecureStringToPlainText $SecureAESKey $AESKey = Convert-HexStringToByteArray -HexString $ClearTextAESKey } Switch ($CipherObject.Encryption) { "DPAPI" { Try { Write-Verbose "Attempting to create a SecureString object from DPAPI cipher text" $SecureStringObj = ConvertTo-SecureString -String $CipherObject.CipherText -ErrorAction Stop $ConvertedString = ConvertFrom-SecureStringToPlainText -StringObj $SecureStringObj -ErrorAction Stop $ConvertedString } Catch { Write-Warning "Unable to decrypt as this user on this machine" Write-Verbose "String protected by Identity: $($CipherObject.DPAPIIdentity)" } } "AES" { Try { Write-Verbose "Attempting to decrypt AES cipher text" $ConvertedString = ConvertFrom-AESCipherText -InputCipherText $CipherObject.CipherText -Key $AESKey -ErrorAction Stop $ConvertedString } Catch { Write-Warning "Failed to decrypt. Incorrect AES key. Check your Master Password." Clear-AESMPVariable } } } } } ### --- PRIVATE FUNCTIONS --- ### #Region - Clear-AESMPVariable.ps1 <# .Synopsis Clear the global variable of the previously stored master password/key .NOTES Version: 1.0 Author: C. Bodett Creation Date: 03/28/2022 Purpose/Change: Initial function development #> Function Clear-AESMPVariable { [cmdletbinding()] Param ( ) Process { Write-Verbose "Clearing global variable where AES key is stored" Remove-Variable -Name "AESMP" -Force -Scope Global -ErrorAction SilentlyContinue } } #Region - Convert-HexStringToByteArray.ps1 <#.Synopsis Converts a hexidecimal string in to an array of bytes .Example Any of the following is valid input 0x41,0x42,0x43,0x44 \x41\x42\x43\x44 41-42-43-44 41424344 #> Function Convert-HexStringToByteArray { [CmdletBinding()] Param ( [Parameter(Mandatory = $true,ValueFromPipeline = $true,Position = 0)] [String]$HexString ) Process { $Regex1 = '\b0x\B|\\\x78|-|,|:' # convert to lowercase and remove all possible deliminating characters $String = $HexString.ToLower() -replace $Regex1,'' # Remove beginning and ending colons, and other detritus. $Regex2 = '^:+|:+$|x|\\' $String = $String -replace $Regex2,'' $ByteArray = if ($String.Length -eq 1) { [System.Convert]::ToByte($String,16) } else { $String -Split '(..)' -ne '' | foreach-object { [System.Convert]::ToByte($_,16) } } Write-Output $ByteArray -NoEnumerate } } #Region - ConvertFrom-AESCipherText.ps1 <# .Synopsis Convert input AES Cipher text to plain text #> Function ConvertFrom-AESCipherText { [cmdletbinding()] param( [Parameter(ValueFromPipeline = $true,Position = 0,Mandatory = $true)] [string]$InputCipherText, [Parameter(Position = 1,Mandatory = $true)] [Byte[]]$Key ) Process { Write-Verbose "Creating new AES Cipher object with supplied key" $AESCipher = Initialize-AESCipher -Key $Key Write-Verbose "Convert input text from Base64" $EncryptedBytes = [System.Convert]::FromBase64String($InputCipherText) Write-Verbose "Using the first 16 bytes as the initialization vector" $AESCipher.IV = $EncryptedBytes[0..15] Write-Verbose "Decrypting AES cipher text" $Decryptor = $AESCipher.CreateDecryptor() $UnencryptedBytes = $Decryptor.TransformFinalBlock($EncryptedBytes, 16, $EncryptedBytes.Length - 16) $ConvertedString = ConvertFrom-Bytes -InputBytes $UnencryptedBytes -Encoding UTF8 $ConvertedString } End { Write-Verbose "Disposing of AES Cipher object" $AESCipher.Dispose() } } #Region - ConvertFrom-Base64.ps1 <# .Synopsis Converts a Base64 string in to plaintext. .Description Takes a Base64 string as a parameter, either directly or from the pipeline, and converts it in to plaintext. .Parameter TextString The Base64 string. Can come from the pipeline. .Parameter Encoding Default encoding is UTF8, but this can be Unicode or UTF8 if you're having problems. .Parameter OutputType Select whether to return the decoded value as a string or a byte array .NOTES Version: 1.0 Author: C. Bodett Creation Date: 9/14/2021 Purpose/Change: Initial function development. #> Function ConvertFrom-Base64 { [cmdletbinding()] Param ( [Parameter(ValueFromPipeline = $true, Position = 0, Mandatory = $true)] [String]$TextString, [Parameter(Position = 1)] [ValidateSet('UTF8','Unicode')] [String]$Encoding = 'UTF8', [Parameter(Position = 2)] [ValidateSet('Bytes','String')] [String]$OutputType = 'String' ) if ($OutputType -eq 'String') { $Decoded = [System.Text.Encoding]::$encoding.GetString([System.Convert]::FromBase64String($TextString)) } else { $Decoded = [System.Convert]::FromBase64String($TextString) } $Decoded } #Region - ConvertFrom-Bytes.ps1 <# .Synopsis Gets string from supplied input bytes #> Function ConvertFrom-Bytes{ [cmdletbinding()] param( [Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$true)] [Byte[]]$InputBytes, [Parameter(Position=1)] [ValidateSet('UTF8','Unicode')] [string]$Encoding = 'Unicode' ) Write-Verbose "Converting from bytes to string using $Encoding encoding" $OutputString = [System.Text.Encoding]::$Encoding.GetString($InputBytes) $OutputString } #Region - ConvertFrom-SecureStringToPlainText.ps1 Function ConvertFrom-SecureStringToPlainText { [cmdletbinding()] param( [parameter(Position=0,HelpMessage="Must provide a SecureString object", ValueFromPipeline,ValueFromPipelineByPropertyName)] [ValidateNotNull()] [System.Security.SecureString]$StringObj ) Process { $BSTR = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($StringObj) $PlainText = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($BSTR) [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR) } End { $PlainText } } #Region - ConvertTo-AESCipherText.ps1 <# .Synopsis Convert input string to AES encrypted cipher text #> Function ConvertTo-AESCipherText { [cmdletbinding()] param( [Parameter(ValueFromPipeline = $true,Position = 0,Mandatory = $true)] [string]$InputString, [Parameter(Position = 1,Mandatory = $true)] [Byte[]]$Key ) Process { $InitializationVector = [System.Byte[]]::new(16) Get-RandomBytes -Bytes $InitializationVector $AESCipher = Initialize-AESCipher -Key $Key $AESCipher.IV = $InitializationVector $ClearTextBytes = ConvertTo-Bytes -InputString $InputString -Encoding UTF8 $Encryptor = $AESCipher.CreateEncryptor() $EncryptedBytes = $Encryptor.TransformFinalBlock($ClearTextBytes, 0, $ClearTextBytes.Length) [byte[]]$FullData = $AESCipher.IV + $EncryptedBytes $ConvertedString = [System.Convert]::ToBase64String($FullData) $DebugInfo = @" `r`n Input String Length : $($InputString.Length) Initialization Vector : $($InitializationVector.Count) Bytes Text Encoding : UTF8 Output Encoding : Base64 "@ Write-Debug $DebugInfo } End { $AESCipher.Dispose() $ConvertedString } } #Region - ConvertTo-AESKey.ps1 <# .Synopsis Function to convert a SecureString object to a unique 32 Byte array for use with AES 256bit encryption .NOTES Version: 3.0 Author: C. Bodett Creation Date: 11/03/2022 Purpose/Change: Changed salt storage method to Base64 encoding for more reliable operation. #> Function ConvertTo-AESKey { [cmdletbinding()] Param ( [Parameter(Mandatory = $true, Position = 0)] [System.Security.SecureString]$SecureStringInput, [Parameter(Mandatory = $false)] [Switch]$ByteArray ) Process { try { Write-Verbose "Retrieving AESKey settings" $Settings = Get-AESKeyConfig -ErrorAction Stop } catch { throw "Failed to get AES Key config settings" } Write-Verbose "Converting Salt to byte array" $SaltBytes = ConvertFrom-Base64 -Textstring $($Settings.Salt) -OutputType Bytes # Temporarily plaintext our SecureString password input. There's really no way around this. Write-Verbose "Converting supplied SecureString text to plaintext" $Password = ConvertFrom-SecureStringToPlainText $SecureStringInput # Create our PBKDF2 object and instantiate it with the necessary values $VMsg = @" `r`n Creating PBKDF2 Object Password....: $("*"*$($Password.Length)) Salt........: $($Settings.Salt) Iterations..: $($Settings.Iterations) Hash........: $($Settings.Hash) "@ Write-Verbose $VMsg $PBKDF2 = New-Object Security.Cryptography.Rfc2898DeriveBytes -ArgumentList @($Password, $SaltBytes, $($Settings.Iterations), $($Settings.Hash)) # Generate our AES Key Write-Verbose "Generating 32 byte key" $Key = $PBKDF2.GetBytes(32) # If the ByteArray switch is provided, return a plaintext byte array, otherwise turn our AES key in to a SecureString object If ($ByteArray) { Write-Verbose "ByteArray switch provided. Returning clear text array of bytes" $KeyOutput = $Key } Else { $KeyAsSecureString = ConvertTo-SecureString -String $([System.BitConverter]::ToString($Key)) -AsPlainText -Force $KeyOutput = $KeyAsSecureString } $KeyOutput } } #Region - ConvertTo-Base64.ps1 <# .Synopsis Converts a plaintext string in to Base64. .Description Takes a plaintext string as a parameter, either directly or from the pipeline, and converts it in to Base64. .Parameter TextString The plaintext string. Can come from the pipeline. .Parameter Encoding Default encoding is UTF8, but this can be Unicode or UTF8 if you're having problems. .NOTES Version: 1.0 Author: C. Bodett Creation Date: 9/14/2021 Purpose/Change: Initial function development. #> Function ConvertTo-Base64{ [cmdletbinding()] Param ( [Parameter(ValueFromPipeline = $true, Position = 0, Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$TextString, [Parameter(ValueFromPipeline = $false, Position = 0, Mandatory = $false)] [ValidateNotNullOrEmpty()] [Byte[]]$Bytes, [Parameter(Position = 1)] [ValidateSet('UTF8','Unicode')] [String]$Encoding = 'UTF8' ) Switch ($PSBoundParameters.Keys) { 'TextString' { $Encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::$Encoding.GetBytes($TextString)) } 'Bytes' { $Encoded = [System.Convert]::ToBase64String($Bytes) } } return $Encoded } #Region - ConvertTo-Bytes.ps1 <# .Synopsis Gets bytes from supplied input string #> Function ConvertTo-Bytes{ [cmdletbinding()] param( [Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$true)] [string]$InputString, [Parameter(Position=1)] [ValidateSet('UTF8','Unicode')] [string]$Encoding = 'Unicode' ) Write-Debug "Converting Input text to bytes with $Encoding encoding" Write-Debug "Input Text: $InputString" $Bytes = [System.Text.Encoding]::$Encoding.GetBytes($InputString) $Bytes } #Region - ConvertTo-CipherObject.ps1 <# .Synopsis Convert output from Protect-String in to a Cipher Object #> Function ConvertTo-CipherObject { [cmdletbinding()] Param ( [String]$B64String ) switch ($B64String[0]) { 'A' { $Encryption = "AES" $CipherText = $B64String.SubString(1) } 'D' { $Encryption = "DPAPI" $CipherText = $B64String.SubString(1,$B64String.IndexOf('?')-1) $DPAPIIdB64 = $B64String.SubString($B64String.IndexOf('?')+1) $DPAPIIdBytes = [System.Convert]::FromBase64String($DPAPIIdB64) $DPAPIIdentity = ConvertFrom-Bytes -InputBytes $DPAPIIdBytes -Encoding UTF8 } default { Write-Verbose "Does not appear to be ProtectStrings module ciphertext" throw } } $CipherObject = try { New-CipherObject -Encryption $Encryption -CipherText $CipherText } catch { Write-Verbose "Unable to create Cipher Object" throw } if ($Encryption -eq "DPAPI") { $CipherObject.DPAPIIdentity = $DPAPIIdentity } $CipherObject } #Region - Get-AESMPVariable.ps1 <# .Synopsis Get the password derived key to a global session variable for future use. .NOTES Version: 1.1 Author: C. Bodett Creation Date: 05/12/2022 Purpose/Change: changed logic from if/ifelse to switch statement #> Function Get-AESMPVariable { [cmdletbinding()] Param ( [Switch]$Boolean ) Process { $SecureAESKey = Try { $Global:AESMP } Catch { # do nothing } Switch ('{0}{1}' -f [int][bool]$SecureAESKey,[int][bool]$Boolean) { "10" { Write-Verbose "Master Password key found" } "11" { Write-Verbose "Master Password key found" return $true } "01" { Write-Verbose "No Master Password key found" return $false } "00" { Write-Verbose "No Master Password key found" Set-MasterPassword $SecureAESKey = Get-AESMPVariable } } $SecureAESKey } } #Region - Get-DPAPIIdentity.ps1 <# .Synopsis Get the current username and computer name #> Function Get-DPAPIIdentity { [cmdletbinding()] Param ( ) Write-Verbose "Current ENV:COMPUTERNAME : $ENV:COMPUTERNAME" Write-Verbose "Current ENV:USERNAME : $ENV:USERNAME" Write-Verbose "Creating DPAPI Identity information" $Output = '{0}\{1}' -f $ENV:COMPUTERNAME,$ENV:USERNAME $Output } #Region - Get-RandomBytes.ps1 <# .Synopsis A Function to leverage the .NET Random Number Generator #> Function Get-RandomBytes { [cmdletbinding()] Param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [Byte[]]$Bytes ) $RNG = New-Object System.Security.Cryptography.RNGCryptoServiceProvider $RNG.GetBytes($Bytes) } #Region - Initialize-AESCipher.ps1 <# .Synopsis A Function to initiate the .NET AESCryptoServiceProvider #> Function Initialize-AESCipher { [cmdletbinding()] Param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [Byte[]]$Key ) $AESServiceProvider = New-Object System.Security.Cryptography.AesCryptoServiceProvider $AESServiceProvider.Key = $Key $AESServiceProvider } #Region - New-CipherObject.ps1 <# .Synopsis Create a new CipherObject #> Function New-CipherObject { [cmdletbinding()] Param ( [Parameter(Mandatory = $true, Position = 0)] [ValidateSet("DPAPI","AES")] [String]$Encryption, [Parameter(Mandatory = $true, Position = 1)] [String]$CipherText ) [CipherObject]::New($Encryption,$CipherText) } #Region - Set-AESMPVariable.ps1 <# .Synopsis Set the password derived key to a global session variable for future use. .NOTES Version: 1.0 Author: C. Bodett Creation Date: 03/27/2022 Purpose/Change: Initial function development #> Function Set-AESMPVariable { [cmdletbinding()] Param ( [Parameter(Mandatory = $true, Position = 0)] [SecureString]$MPKey ) Process { Write-Verbose "Creating new variable globally to store AES Key" New-Variable -Name "AESMP" -Value $MPKey -Option AllScope -Scope Global -Force } } ### --- CLASS DEFINITIONS --- ### #Region - CipherObject.ps1 Class CipherObject { [String] $Encryption [String] $CipherText hidden[String] $DPAPIIdentity CipherObject ([String]$Encryption, [String]$CipherText) { $this.Encryption = $Encryption $this.CipherText = $CipherText $this.DPAPIIdentity = $null } [String] ToCompressed() { if ($this.Encryption -eq "AES") { return 'A{0}' -f $this.CipherText } else { $JSONBytes = ConvertTo-Bytes -InputString $this.DPAPIIdentity -Encoding UTF8 $EncodedOutput = [System.Convert]::ToBase64String($JSONBytes) return 'D{0}?{1}' -f $this.CipherText, $EncodedOutput } } } |