Skip to content

Instantly share code, notes, and snippets.

@markekraus
Created February 18, 2018 19:41
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markekraus/135c593e20a4459149944ba5af9523ce to your computer and use it in GitHub Desktop.
Save markekraus/135c593e20a4459149944ba5af9523ce to your computer and use it in GitHub Desktop.
PowerShell Functions to convert a string to a base64 representation of the KMS encryoted string and to convert back to an unencrypted string
function ConvertTo-Base64KMSEncryptedString {
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true
)]
[String[]]
$String,
[Parameter(
Mandatory = $true
)]
[string]
$KeyId,
[hashtable]$EncryptionContext
)
process {
foreach ($SourceString in $String) {
$byteArray = [System.Text.Encoding]::UTF8.GetBytes($SourceString)
$stringStream = [System.IO.MemoryStream]::new($ByteArray)
try {
$Params = @{
KeyId = $KeyId
Plaintext = $stringStream
ErrorAction = 'Stop'
}
if ($EncryptionContext) {
$Params['EncryptionContext'] = $EncryptionContext
}
$KMSResult = Invoke-KMSEncrypt @Params
[System.Convert]::ToBase64String($KMSResult.CiphertextBlob.ToArray())
}
finally {
if ($stringStream) { $stringStream.Dispose() }
if ($KMSResult.CiphertextBlob) { $KMSResult.CiphertextBlob.Dispose() }
}
}
}
}
function ConvertFrom-Base64KMSEncryptedString {
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true
)]
[String[]]
$EncryptedString,
[hashtable]$EncryptionContext
)
process {
foreach ($SourceString in $EncryptedString) {
try{
$byteArray = [System.Convert]::FromBase64String($SourceString)
}
Catch {
Write-Error -ErrorRecord $_
continue
}
$stringStream = [System.IO.MemoryStream]::new($byteArray)
try {
$Params = @{
CiphertextBlob = $stringStream
ErrorAction = 'Stop'
}
if ($EncryptionContext) {
$Params['EncryptionContext'] = $EncryptionContext
}
$KMSResult = Invoke-KMSDecrypt @Params
$reader = [System.IO.StreamReader]::new($KMSResult.Plaintext)
$reader.ReadToEnd()
}
finally {
if ($reader){ $reader.Dispose() }
if ($stringStream){ $stringStream.Dispose() }
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment