创建CMK

第二节我们提到,KMS加密有两种场景:

  • 对密码进行加密。这种情况下密码大小一般小于4K
  • 对大文本进行加密,例如上G的数据。此时需要使用data key来加密。

本节我们对第一种场景进行测试

创建CMK

进行aws控制台的KMS服务,点击Create Key:

image-20250308192928618

使用对称加密,其他选项保持默认:

image-20250308192953425

为KMS命名:

image-20250308193017542

其他选项保持默认,进入最后一步创建:

image-20250308193105357

等待创建完成。

使用CMK对密码进行加密和解密

在这个例子中,我们对字符使用KMS进行加密,得到:encrypted.txt

然后对encrypted.txt进行解密,得到decrypted.txt

Encrypt API

aws kms encrypt --key-id 1234abcd-12ab-34cd-56ef-1234567890ab --plaintext "Hello, this is my secret text" --output text --query CiphertextBlob | base64 --decode > EncryptedSecret

Key-id 可从console中找到:

  • image-20250308194616469
  • –plaintext : 要加密的字符串
  • –output text –query CiphertextBlob 控制输出, CiphertextBlob 包含加密后的密文结果, 这样避免了输出包含其他元数据信息
  • 默认输出为base64 encode之后的数据,解码需要进行base64 decode.
  • 将文件保存到ExampleEncryptedFile里面,这个文件包含了原始数据的加密形式。

示例:

aws kms encrypt  --cli-binary-format raw-in-base64-out --key-id a323129b-c984-42ec-a2da-936874fafa4a --plaintext "Hello, this is my secret text" --output text --query CiphertextBlob | base64 --decode > encrypted.txt

在AWS CLI v2中,使用--cli-binary-format raw-in-base64-out参数可以自动将字符串转成base64,不然需要先将字符串转成base64格式再传入

image-20250308195521672

如果不进行base64 decode,则加密的结果为一串base64字符串:

image-20250308195620167


使用kms加密时,最终形式一般为:

aws kms encrypt --key-id 3122a751-2cbd-4950-a056-c5dca7104679 --plaintext "Hello world" --query CiphertextBlob --output text| base64 --decode > encrypted.txt

Decrypt API

形式:

aws kms decrypt --ciphertext-blob fileb://ExampleEncryptedFile --output text --query Plaintext | base64 --decode > ExamplePlaintextFile

示例:

aws kms decrypt --ciphertext-blob fileb://encrypted.txt --output text --query Plaintext | base64 --decode > decrypted.txt

image-20250308195909231

Re-encrypt

如果我们查看KMS的API,发现还有一个re-encrypt操作:

image-20250308200034407

ReEncrypt 是 AWS Key Management Service (KMS) 提供的一个特殊 API,用于在不暴露明文数据的情况下,使用新的 KMS 密钥重新加密已加密的数据。这是一项关键安全功能,允许在保持数据机密性的同时更改用于保护数据的密钥。

ReEncrypt API 的主要目的是在服务器端一次性操作中解密密文数据,并立即使用新密钥重新加密,确保明文数据从不离开 AWS KMS 安全边界。整个过程中,原始明文数据不会返回给客户端,也不会在传输过程中暴露。