Skip to content

Instantly share code, notes, and snippets.

@mkropat
Created December 29, 2019 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkropat/d7eab7ee8a1ed97fb978e51d4b22150e to your computer and use it in GitHub Desktop.
Save mkropat/d7eab7ee8a1ed97fb978e51d4b22150e to your computer and use it in GitHub Desktop.
function Compute-Sha256($Str) {
$sha256 = New-Object System.Security.Cryptography.SHA256Managed
$sha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($Str))
}
function Get-RandomBytes($Size) {
$rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$bytes = [System.Byte[]]::new($Size)
$rng.GetBytes($bytes)
$bytes
}
function Encrypt-Aes256($Key, $Iv, $Data) {
$aes = New-Object System.Security.Cryptography.AesCryptoServiceProvider
$aes.KeySize = 256
$aes.Key = Compute-Sha256($Key)
$aes.IV = $Iv
$encryptor = $aes.CreateEncryptor()
$encryptedBytes = $aes.IV + $encryptor.TransformFinalBlock($Data, 0, $Data.Length)
([System.Convert]::ToBase64String($encryptedBytes))
}
$key = (Get-RandomBytes(256/8) | ForEach-Object ToString X2) -join ''
Write-Host "Send the following password via one channel:"
Write-Host
Write-Host "Password: $key"
Write-Host
Write-Host "Then using a different channel, send the following snippet:"
Write-Host
$cipherText = Encrypt-Aes256 `
-Key $key `
-Iv (Get-RandomBytes(128/8)) `
-Data ([System.Text.Encoding]::UTF8.GetBytes(@($input) -join "`n"))
Write-Host 'function Decrypt($CipherText) {
$encrypted = [Convert]::FromBase64String($CipherText)
$sha256 = New-Object Security.Cryptography.SHA256Managed
$aes = New-Object Security.Cryptography.AesCryptoServiceProvider
$aes.Key = $sha256.ComputeHash(
[Text.Encoding]::UTF8.GetBytes(
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR(
(Read-Host -AsSecureString "Password"))).Trim()))
$aes.IV = $encrypted[0..15]
$decryptor = $aes.CreateDecryptor();
Write-Host ([Text.Encoding]::UTF8.GetString(
$decryptor.TransformFinalBlock($encrypted, 16, $encrypted.Length - 16)))
}'
Write-Host "Decrypt '$cipherText'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment