How can I read from the memory stream of the "Plaintext" property returned by New-KMSDataKey? How can I read from the memory stream of the "Plaintext" property returned by New-KMSDataKey? powershell powershell

How can I read from the memory stream of the "Plaintext" property returned by New-KMSDataKey?


In short,

# generate a data key$KMSKeyS3 = New-KMSDataKey -KeyId $KMSKeySource -KeySpec AES_256 -Region "ap-southeast-2"[byte[]]$plaintextDataKey = $KMSKeyS3.Plaintext.ToArray()[byte[]]$encryptedDataKey = $KMSKeyS3.CiphertextBlob.ToArray()[string]$encryptedDatakeyBase64 = $([Convert]::ToBase64String($encryptedDataKey))

See this answer to a question on PowerShell and KMS for a comprehensive answer including tested encryption and decryption scripts, and base64 conversion.