src/encryption/public/Get-EncryptedString.ps1
<#
.SYNOPSIS Encrypts a string with a passphrase using Rijndael / AES128 .EXAMPLE $pass = "SecretPassword" | ConvertTo-SecureString -AsPlainText -Force $encrypted = "Secret Text!" | Get-EncryptedString -Passphrase $pass #> Function Get-EncryptedString { Param( [Parameter(Mandatory)][SecureString]$Passphrase, [Parameter(Mandatory, ValueFromPipeline)][string]$Text ) Process { $derivationIterations = 1000 # Salt and IV is randomly generated each time, but is preprended to encrypted cipher text # so that the same Salt and IV values can be used when decrypting. $saltStringBytes = Get-RandomBytes -NumBytes 32 $ivStringBytes = Get-RandomBytes -NumBytes 16 $plainTextBytes = [System.Text.Encoding]::UTF8.GetBytes($Text); try { $password = [System.Security.Cryptography.Rfc2898DeriveBytes]::new( ($Passphrase | ConvertFrom-SecureString -AsPlainText), $saltStringBytes, $derivationIterations) $keyBytes = $password.GetBytes(32); $symmetricKey = [System.Security.Cryptography.RijndaelManaged]::new() $symmetricKey.BlockSize = 128 $symmetricKey.Mode = [System.Security.Cryptography.CipherMode]::CBC $symmetricKey.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 $encryptor = $symmetricKey.CreateEncryptor($keyBytes, $ivStringBytes) $memoryStream = [System.IO.MemoryStream]::new() $cryptoStream = [System.Security.Cryptography.CryptoStream]::new( $memoryStream, $encryptor, "Write") $cryptoStream.Write($plainTextBytes, 0, $plainTextBytes.Length); $cryptoStream.FlushFinalBlock(); # Create the final bytes as a concatenation of the random salt bytes, # the random iv bytes and the cipher bytes. $cipherTextBytes = $saltStringBytes $cipherTextBytes = $cipherTextBytes + $ivStringBytes $cipherTextBytes = $cipherTextBytes + $memoryStream.ToArray() $memoryStream.Close(); $cryptoStream.Close(); return [Convert]::ToBase64String($cipherTextBytes) } finally { $password ? $password.Dispose() : $null $symmetricKey ? $symmetricKey.Dispose() : $null $encryptor ? $encryptor.Dispose() : $null $memoryStream ? $memoryStream.Dispose() : $null $cryptoStream ? $cryptoStream.Dispose() : $null } } } |