ProtectStrings.psm1
#Region '.\Classes\CipherObject.ps1' -1 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 = [System.Text.Encoding]::UTF8.GetBytes($this.DPAPIIdentity) $EncodedOutput = [System.Convert]::ToBase64String($JSONBytes) return 'D{0}?{1}' -f $this.CipherText, $EncodedOutput } } } #EndRegion '.\Classes\CipherObject.ps1' 20 #Region '.\Private\ConvertFrom-AESCipherText.ps1' -1 function ConvertFrom-AESCipherText { <# .SYNOPSIS Convert input AES Cipher text to plain text .DESCRIPTION Converts input AES cipher text to plain text. This is a private function that won't be exposed in the session. .PARAMETER InputCipherText The cipher text to convert .PARAMETER Key A byte array containing the 256-bit AES key .EXAMPLE ConvertFrom-AESCipherText -InputCipherText $CipherText -Key $AESKey #> [cmdletbinding()] [OutputType([string])] 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" $AESProvider = [System.Security.Cryptography.AesCryptoServiceProvider]::Create() $AESProvider.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" $AESProvider.IV = $EncryptedBytes[0..15] Write-Verbose "Decrypting AES cipher text" $Decryptor = $AESProvider.CreateDecryptor() $UnencryptedBytes = $Decryptor.TransformFinalBlock($EncryptedBytes, 16, $EncryptedBytes.Length - 16) $ConvertedString = [System.Text.Encoding]::UTF8.GetString($UnencryptedBytes) $ConvertedString } end { Write-Verbose "Disposing of AES Cipher object" $AESProvider.Dispose() } } #EndRegion '.\Private\ConvertFrom-AESCipherText.ps1' 43 #Region '.\Private\ConvertFrom-SecureStringToPlainText.ps1' -1 function ConvertFrom-SecureStringToPlainText { <# .SYNOPSIS Decrypts a secure string from the memory object in to plain text .DESCRIPTION Decrypts a secure string from the memory object in to plain text. This is a private function and won't be exposed to the session. .PARAMETER StringObj The secure string object reference .EXAMPLE ConvertFrom-SecureStringToPlainText -StringObj $SecureString #> [cmdletbinding()] [OutputType([string])] param( [System.Security.SecureString]$StringObj ) $BSTR = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($StringObj) $PlainText = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($BSTR) [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR) $PlainText } #EndRegion '.\Private\ConvertFrom-SecureStringToPlainText.ps1' 23 #Region '.\Private\Convert-HexStringToByteArray.ps1' -1 function Convert-HexStringToByteArray { <# .SYNOPSIS converts a hexidecimal string in to an array of bytes .DESCRIPTION converts a hexidecimal string in to an array of bytes. This is a private function that won't be exposed to the session. .PARAMETER HexString The hexadecimal string to convert in to a byte array Any of the following is valid input 0x41,0x42,0x43,0x44 \x41\x42\x43\x44 41-42-43-44 41424344 .EXAMPLE Convert-HexStringToByteArray -HexString 41-42-43-44 #> [CmdletBinding()] [OutputType([string])] 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 } } #EndRegion '.\Private\Convert-HexStringToByteArray.ps1' 45 #Region '.\Private\ConvertTo-AESCipherText.ps1' -1 function ConvertTo-AESCipherText { <# .SYNOPSIS Convert input string to AES encrypted cipher text .DESCRIPTION Convert input string to AES encrypted cipher text. This is a private function and won't be exposed to the session. .PARAMETER InputString The string to encrypt with AES256 .PARAMETER Key A byte array containing the 256-bit key used with AES .EXAMPLE ConvertTo-AESCipherText -InputString "secret" -Key $Key #> [cmdletbinding()] [OutputType([string])] param( [Parameter(Position = 0,Mandatory = $true)] [string]$InputString, [Parameter(Position = 1,Mandatory = $true)] [byte[]]$Key ) $InitializationVector = [System.Byte[]]::new(16) $RNG = [System.Security.Cryptography.RandomNumberGenerator]::Create() $RNG.GetBytes($InitializationVector) $AESProvider = [System.Security.Cryptography.AesCryptoServiceProvider]::Create() $AESProvider.Key = $Key $AESProvider.IV = $InitializationVector $ClearTextBytes = [System.Text.Encoding]::UTF8.GetBytes($InputString) $Encryptor = $AESProvider.CreateEncryptor() $EncryptedBytes = $Encryptor.TransformFinalBlock($ClearTextBytes, 0, $ClearTextBytes.Length) [byte[]]$FullData = $AESProvider.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 $AESProvider.Dispose() $ConvertedString } #EndRegion '.\Private\ConvertTo-AESCipherText.ps1' 44 #Region '.\Private\ConvertTo-AESKey.ps1' -1 function ConvertTo-AESKey { <# .SYNOPSIS Function to convert a SecureString object to a unique 32 Byte array for use with AES 256bit encryption .DESCRIPTION Function to convert a SecureString object to a unique 32 Byte array for use with AES 256bit encryption. This is a private function and will not be exposed to the session. .PARAMETER SecureStringInput The SecureString object representing the master password that will be converted to a key .PARAMETER ByteArray Switch parameter to return a byte array .EXAMPLE CovnertTo-AESKey -SecureStringInput $SecureString #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Justification = 'Necessary')] param ( [Parameter(Mandatory = $true, Position = 0)] [System.Security.SecureString]$SecureStringInput, [Parameter(Mandatory = $false)] [Switch]$ByteArray ) 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 = [System.Convert]::FromBase64String($($Settings.Salt)) # 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 } #EndRegion '.\Private\ConvertTo-AESKey.ps1' 58 #Region '.\Private\ConvertTo-CipherObject.ps1' -1 function ConvertTo-CipherObject { <# .SYNOPSIS Convert output from Protect-String in to a Cipher Object .DESCRIPTION Convert output from Protect-String in to a Cipher Object. This is a private function that won't be exposed to the session. .PARAMETER B64String The base64 string to instantiate in to a cipher object .EXAMPLE ConvertTo-CipherObject -B64String VQ== #> [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 = [System.Text.Encoding]::UTF8.GetString($DPAPIIdBytes) } 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 } #EndRegion '.\Private\ConvertTo-CipherObject.ps1' 48 #Region '.\Private\New-CipherObject.ps1' -1 function New-CipherObject { <# .SYNOPSIS Create a new CipherObject .DESCRIPTION Create a new CipherObject. This is a private function and won't be exposed to the session. .PARAMETER Encryption The encryption type to use: DPAPI or AES .PARAMETER CipherText The cipher text to later be decrypted .EXAMPLE New-CipherObject -Encryption AES -CipherText "AQ==" #> [cmdletbinding()] [OutputType([CipherObject])] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions','',Justification='Does not actually change system state')] param ( [Parameter(Mandatory = $true, Position = 0)] [ValidateSet("DPAPI","AES")] [string]$Encryption, [Parameter(Mandatory = $true, Position = 1)] [string]$CipherText ) [CipherObject]::New($Encryption,$CipherText) } #EndRegion '.\Private\New-CipherObject.ps1' 27 #Region '.\Public\Clear-MasterPassword.ps1' -1 function Clear-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:\> Clear-MasterPassword This will erase the currently saved master password. #> [cmdletbinding()] param ( ) Write-Verbose "Removing master password from current session" Remove-Variable -Name "AESMP" -Force -Scope Global -ErrorAction SilentlyContinue } #EndRegion '.\Public\Clear-MasterPassword.ps1' 19 #Region '.\Public\Export-MasterPassword.ps1' -1 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 #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars','',Justification='Required for QoL')] 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 ) $SecureAESKey = $Global:AESMP if ($SecureAESKey) { Write-Verbose "Stored AES key found" $ClearTextAESKey = ConvertFrom-SecureStringToPlainText $SecureAESKey Write-Verbose "Converting to Base64 before export" $EncodedKey = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($ClearTextAESKey)) Write-Verbose "Saving to $Filepath with Encoded key:" Out-File -FilePath $FilePath -InputObject $EncodedKey -Force } else { Write-Warning "No key found to export" } } #EndRegion '.\Public\Export-MasterPassword.ps1' 43 #Region '.\Public\Get-AESKeyConfig.ps1' -1 function Get-AESKeyConfig { <# .SYNOPSIS Function to retrieve settings for use with PBKDF2 to create an AES Key .DESCRIPTION Function to retrieve the PBKDF2 parameters that are currently set. These parameters control the strength of the derived key. Ships with OWASP recommended defaults but can be changed using the Set-AESKeyConfig function. Use Get-AESKeyconfig to confirm current settings. .EXAMPLE PS> Get-AESKeyConfig Hash Iterations Salt ---- ---------- ---- SHA384 1000000 fMK9w4HDtMO4d8Oa4pmAw6U+fknCqWvil4Q9w73DscOtw64= #> [cmdletbinding()] param ( ) # check to see if we're on Windows or not if ($IsWindows -or $ENV:OS) { $Windows = $true } else { $Windows = $false } if ($Windows) { $SettingsPath = Join-Path -Path $Env:APPDATA -ChildPath "ProtectStrings\Settings.json" } else { $SettingsPath = Join-Path -Path ([Environment]::GetEnvironmentVariable("HOME")) -ChildPath ".local/share/powershell/Modules/ProtectStrings/Settings.json" } if (Test-Path $SettingsPath) { try { $Settings = Get-Content -Path $SettingsPath | ConvertFrom-Json } catch { throw $_ } } else { # Default settings $Settings = @{ Salt = 'fMK9w4HDtMO4d8Oa4pmAw6U+fknCqWvil4Q9w73DscOtw64=' Iterations = 600000 Hash = 'SHA256' } } $Settings } #EndRegion '.\Public\Get-AESKeyConfig.ps1' 47 #Region '.\Public\Get-MasterPassword.ps1' -1 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. .PARAMETER Boolean Will return true/false instead of returning a SecureString object .EXAMPLE PS C:\> Get-MasterPassword System.Security.SecureString #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars','',Justification='Required for QoL')] [OutputType([System.Security.SecureString], [bool])] param ( [Switch]$Boolean ) Write-Verbose "Checking for stored AES key" if ($Boolean) { if ($Global:AESMP) { return $true } else { return $false } } else { $Global:AESMP } } #EndRegion '.\Public\Get-MasterPassword.ps1' 32 #Region '.\Public\Import-MasterPassword.ps1' -1 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. #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Justification = 'Necessary')] 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 = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($EncodedKey)) Write-Verbose "Storing AES Key to current session" $SecureAESKey = ConvertTo-SecureString -String $ClearTextAESKey -AsPlainText -Force New-Variable -Name "AESMP" -Value $SecureAESKey -Option AllScope -Scope Global -Force } } } #EndRegion '.\Public\Import-MasterPassword.ps1' 50 #Region '.\Public\Protect-String.ps1' -1 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. #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars','',Justification='Required for QoL')] 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" if (Get-MasterPassword -Boolean) { $SecureAESKey = Get-MasterPassword } else { Write-Verbose "No Master Password key found" Set-MasterPassword $SecureAESKey = Get-MasterPassword } $SecureAESKey = $Global:AESMP $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." } } Add-Type -AssemblyName System.Security } process { switch ($Encryption) { "DPAPI" { try { Write-Verbose "Converting string text to a SecureString object" $StringBytes = [System.Text.Encoding]::UTF8.GetBytes($InputString) $DPAPIBytes = [System.Security.Cryptography.ProtectedData]::Protect($StringBytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser) $ConvertedString = [System.Convert]::ToBase64String($DPAPIBytes) $CipherObject = New-CipherObject -Encryption "DPAPI" -CipherText $ConvertedString $CipherObject.DPAPIIdentity = '{0}\{1}' -f $ENV:COMPUTERNAME,$ENV:USERNAME Write-Verbose "DPAPI Identity: $($CipherObject.DPAPIIdentity)" $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 $CipherObject.ToCompressed() } catch { Write-Error $_ } } } } } #EndRegion '.\Public\Protect-String.ps1' 87 #Region '.\Public\Set-AESKeyConfig.ps1' -1 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. .EXAMPLE PS> Set-AESKeyConfig -Hash SHA512 -Iterations 1000000 This will leave the default salt but change the hash algorithm to SHA512 (from SHA256) and increase the iterations from 600,000 to 1,000,000. #> [cmdletbinding(DefaultParameterSetName = 'none',SupportsShouldProcess)] 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 # check to see if we're on Windows or not if ($IsWindows -or $ENV:OS) { $Windows = $true } else { $Windows = $false } if ($Windows) { $SettingsPath = Join-Path -Path $Env:APPDATA -ChildPath "ProtectStrings\Settings.json" } else { $SettingsPath = Join-Path -Path ([Environment]::GetEnvironmentVariable("HOME")) -ChildPath ".local/share/powershell/Modules/ProtectStrings/Settings.json" } if (-not($Defaults)) { switch ($PSBoundParameters.Keys) { 'SaltString' { try { $Settings.Salt = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($SaltString)) } catch { Throw $_ } } 'SaltBytes' { try { $Settings.Salt = [System.Convert]::ToBase64String($SaltBytes) } catch { Throw $_ } } 'Iterations' { $Settings.Iterations = $Iterations } 'Hash' { $Settings.Hash = $Hash } } $VMsg = @" `r`n Saving settings to $SettingsPath Salt........: $($Settings.Salt) Iterations..: $($Settings.Iterations) Hash........: $($Settings.Hash) "@ Write-Verbose $VMsg try { if (Test-Path $SettingsPath) { $Settings | ConvertTo-Json | Out-File -FilePath $SettingsPath -Force } else { New-Item -Path $SettingsPath -Force | Out-Null $Settings | ConvertTo-Json | Out-File -FilePath $SettingsPath } } catch { throw $_ } } else { try { Write-Verbose "Removing settings file at $($SettingsPath)" Remove-Item -Path $SettingsPath -Force -ErrorAction Stop } catch [System.Management.Automation.ItemNotFoundException] { Write-Warning "No settings file found" } catch { throw $_ } } } #EndRegion '.\Public\Set-AESKeyConfig.ps1' 110 #Region '.\Public\Set-MasterPassword.ps1' -1 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. #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions','',Justification='Does not actually change system state')] 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" New-Variable -Name "AESMP" -Value $SecureAESKey -Option AllScope -Scope Global -Force } #EndRegion '.\Public\Set-MasterPassword.ps1' 42 #Region '.\Public\Unprotect-String.ps1' -1 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. #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars','',Justification='Required for QoL')] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [string]$InputString ) begin { Add-Type -AssemblyName System.Security } 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 = $Global:AESMP $ClearTextAESKey = ConvertFrom-SecureStringToPlainText $SecureAESKey $AESKey = Convert-HexStringToByteArray -HexString $ClearTextAESKey } switch ($CipherObject.Encryption) { "DPAPI" { try { Write-Verbose "Attempting to decrypt with DPAPI" $DPAPIBytes = [System.Convert]::FromBase64String($CipherObject.CipherText) $DecryptedBytes = [System.Security.Cryptography.ProtectedData]::UnProtect($DPAPIBytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser) $ConvertedString = [System.Text.Encoding]::UTF8.GetString($DecryptedBytes) $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-MasterPassword } } } } } #EndRegion '.\Public\Unprotect-String.ps1' 87 |