StringEncryption.psm1
#region Encrypt-String Function Encrypt-String { <# .SYNOPSIS Encrypts a string. .DESCRIPTION The Encrypt-String function encrypts a string using a provided key in order to secure it. .PARAMETER String The string to encrypt. .PARAMETER Key The key to use. .EXAMPLE $encrypted = Encrypt-String -String "Plain Text" -Key "1234567890123456" This command will encrypt the "Plain Text" string and save the result in the "encrypted" variable. #> Param ( [Parameter( Mandatory = $true, Position = 0 )] [string]$String, [Parameter( Mandatory = $true, Position = 1 )] [string]$Key ) Begin {} Process { # Convert the key to bytes # Check if the key has the necessary length if( ($Key.Length -ne 16) -and ($Key.Length -ne 24) -and ($Key.Length -ne 32)) { Write-Error "The key length must be 16, 24 or 32." return } $Bytes = [System.Text.Encoding]::ASCII.GetBytes($Key) # Convert the string to secure string $SecureString = New-Object System.Security.SecureString $chars = $String.ToCharArray() foreach($c in $chars) { $SecureString.AppendChar($c) } # Convert the secure string to encrypted string $EncryptedString = $SecureString | ConvertFrom-SecureString -key $Bytes # Return the encrypted string Write-Output $EncryptedString } End {} } #endregion #region Decrypt-String Function Decrypt-String { <# .SYNOPSIS Decrypts an encrypted string. .DESCRIPTION The Decrypt-String function decrypts a string that has been encrypted using a provided key. .PARAMETER EncryptedString The string to decrypt. .PARAMETER Key The key to use. .EXAMPLE $encrypted = Encrypt-String -String "Plain Text" -Key "1234567890123456" This command will encrypt the "Plain Text" string and save the result in the "encrypted" variable. #> Param ( [Parameter( Mandatory = $true, Position = 0 )] [string]$EncryptedString, [Parameter( Mandatory = $true, Position = 1 )] [string]$Key ) Begin {} Process { # Convert the key to bytes # Check if the key has the necessary length if( ($Key.Length -ne 16) -and ($Key.Length -ne 24) -and ($Key.Length -ne 32)) { Write-Error "The key length must be 16, 24 or 32." return } $Bytes = [System.Text.Encoding]::ASCII.GetBytes($Key) # Covert the encrypted string to a secure string $SecureString = $EncryptedString | ConvertTo-SecureString -Key $Bytes # Create a credential object in order to get the plaintext string from the secure string $credentials = New-Object System.Management.Automation.PSCredential ("User", $SecureString) $string = $credentials.GetNetworkCredential().Password # return the plain text string Write-Output $string } End {} } #endregion #region Exports Export-ModuleMember -Function Encrypt-String Export-ModuleMember -Function Decrypt-String #endregion |