0
votes

I'm trying to encrypt and decrypt content with the aws cli on powershell (not the powershell specific one but the standard one)

Here is my way to do it and that seems closer to the truth:

$input = "foo"
$file_path = "$(pwd)\file"
$region = "eu-west-1"

# ENCRYPT
$ciphertextblob =
   aws kms encrypt `
     --region $region `
     --key-id "a266be0d-304b-4gf2-8b75-021ba4b0d23a" `
     --plaintext $input |
   ConvertFrom-Json |
   Foreach-Object { $_.CiphertextBlob }

$encrypted = [System.Convert]::FromBase64String($ciphertextblob)
[io.file]::WriteAllBytes($file_path, $encrypted)

# DECRYPT
$decrypt =
   aws kms decrypt `
     --region $region `
     --ciphertext-blob "fileb://$file_path"

# SHOW
$decrypt

and the result is

{
    "Plaintext": "Zm9v",
    "KeyId": "arn:aws:kms:eu-west-1:639530368848:key/a266be0d-304b-4gf2-8b75-021ba4b0d23a"
}

As you can see:

  • I define an input "foo" that becomes "Zm9v" at the end
  • "Zm9v" is not base64
  • I take the encrypt command result, transform from JSON to Powershell object then take the CiphertextBlob
  • I decode that from base64 to plaintext and write it in a binary file with WriteAllBytes
  • finally I use the fileb to read the binary file with the decrypt command

So my problem seems:

that I must have a missing encoding somewhere ... if someone could help me progress :-D

Regards, Thibault

1

1 Answers

0
votes

My mistake was to thought $decrypt to not be base64.

Here is the full working example:

$input = "foo"
$file_path = "$(pwd)\file"
$region = "eu-west-1"

# ENCRYPT
$ciphertextblob =
   aws kms encrypt `
     --region $region `
     --key-id "a266be0d-304b-4gf2-8b75-021ba4b0d23a" `
     --plaintext $input |
   ConvertFrom-Json |
   Foreach-Object { $_.CiphertextBlob }

$encrypted = [System.Convert]::FromBase64String($ciphertextblob)
[io.file]::WriteAllBytes($file_path, $encrypted)

# DECRYPT
$decrypt_base64 =
   aws kms decrypt `
     --region $region `
     --ciphertext-blob "fileb://$file_path" |
   ConvertFrom-Json |
   %{ $_.Plaintext }

$decrypt_plaintext = [System.Text.Encoding]::UTF8.GetString(
   [System.Convert]::FromBase64String($decrypt_base64)
)

# SHOW
$decrypt_plaintext

And the result as expected is:

foo