Last active
March 24, 2022 11:59
-
-
Save PanosGreg/33d5453f4df501cb250e98262c5ce804 to your computer and use it in GitHub Desktop.
Encryption & Decryption using native PowerShell Convert functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Encryption & Decryption via ConvertFrom-SecureString and ConvertTo-SecureString | |
## This is Symetrical encryption. Which means the same key is used to both encrypt and decrypt. | |
## The encryption method is based on AES 256bit. | |
$KeyFile = 'c:\temp\AWS.key' | |
$EncFile = 'c:\temp\AWS.aes' | |
$DecFile = 'c:\temp\AWS.json' | |
##### Create Sample Text | |
$Text = [pscustomobject] @{ | |
TypeName = 'AWS.Account' | |
Access = '..xxx' | |
Secret = '..yyy' | |
Region = 'eu-west-1' | |
Account = '..111' | |
} | ConvertTo-Json | |
$Text | Out-File $DecFile | |
##### Generate a password | |
$Bytes = [byte[]]::new(1024) | |
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Bytes) | |
$SpecialChars = @(40,41,33,64,36,37,45,61,46,63,42,59,38) | |
$Filter = { | |
($_ -ge 97 -and $_ -le 122) -or # a - z | |
($_ -ge 65 -and $_ -le 90) -or # A - Z | |
($_ -ge 50 -and $_ -le 57) -or # 2 - 9 | |
($SpecialChars -contains $_) # ()!@$%-=.?*;& | |
} | |
$text = [Text.Encoding]::ASCII.GetString(($Bytes | where $Filter)) | |
$pass = $text.Substring(0,128) | |
# create a key by hashing the password | |
$algo = [System.Security.Cryptography.HashAlgorithm]::Create('SHA256') | |
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pass) | |
$StrB = [System.Text.StringBuilder]::new() | |
$algo.ComputeHash($bytes) | foreach {[void]$StrB.Append($_.ToString('x2'))} | |
$Key = $StrB.ToString(0,32) | Out-File $KeyFile -Encoding utf8 -NoNewline | |
##### Encrypt the File | |
$key = [byte[]][char[]](Get-Content $KeyFile -Raw) | |
$Text = Get-Content $DecFile -Raw | |
$SecStr = ConvertTo-SecureString -String $Text -AsPlainText -Force | |
$EncStr = $SecStr | ConvertFrom-SecureString -Key $Key # <-- encryption | |
$EncStr | Out-File $EncFile -Encoding utf8 -NoNewline | |
##### Decrypt the File | |
$key = [byte[]][char[]](Get-Content $KeyFile -Raw -Encoding UTF8) | |
$EncStr = Get-Content $EncFile -Raw -Encoding UTF8 | |
$SecStr = $EncStr | ConvertTo-SecureString -Key $Key # <-- decryption | |
$BinStr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecStr) | |
$Text = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BinStr) | |
$Text | ConvertFrom-Json | |
# the Encryption is done via: ConvertFrom-SecureString | |
# the Decryption is done via: ConvertTo-SecureString |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment