AWS CLI:AWS KMS 使用 PowerShell 加密/解密



我正在尝试使用 powershell 上的 aws cli 加密和解密内容(不是特定于 powershell 的,而是标准的(

这是我的方法,这似乎更接近事实:

$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

结果是

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

如您所见:

  • 我定义了一个输入"foo",最后变成"Zm9v">
  • "Zm9v"不是基数64
  • 我采用加密命令结果,从JSON转换为Powershell对象,然后获取CiphertextBlob
  • 我将其从base64解码为纯文本,并使用WriteAllBytes将其写入二进制文件中
  • 最后我使用 fileb 通过解密命令读取二进制文件

所以我的问题似乎:

我一定在某处缺少编码......如果有人能帮助我进步:-D

问候 蒂博

我的错误是认为$decrypt不是base64。

以下是完整的工作示例:

$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

结果如预期的那样是:

foo

最新更新