使用 适用于 PHP 的 Amazon SDK 版本 3 来加密和解密 Amazon KMS 数据密钥 - 适用于 PHP 的 Amazon SDK
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 适用于 PHP 的 Amazon SDK 版本 3 来加密和解密 Amazon KMS 数据密钥

数据密钥是可用于加密数据的加密密钥,包括大量数据和其他数据加密密钥。

可以使用 Amazon Key Management Service 的 (Amazon KMS) Amazon KMS key 来生成、加密和解密数据密钥。

以下示例演示如何:

  • 使用 Encrypt 加密数据密钥。

  • 使用 Decrypt 解密数据密钥。

  • 使用 ReEncrypt 通过新的 KMS 密钥来重新加密数据密钥。

适用于 PHP 的 Amazon SDKGitHub 上提供了的所有示例代码。

凭证

运行示例代码之前,请配置您的 Amazon 凭证,如 Amazon 使用 适用于 PHP 的 Amazon SDK 版本 3 进行身份验证 中所述。然后导入 适用于 PHP 的 Amazon SDK,如 安装适用于 PHP 的 Amazon SDK 版本 3 中所述。

有关使用 Amazon Key Management Service (Amazon KMS) 的更多信息,请参阅 Amazon KMS 开发人员指南

Encrypt

Encrypt 操作专用于加密数据密钥,但并不常用。GenerateDataKeyGenerateDataKeyWithoutPlaintext 操作会返回加密的数据密钥。将加密的数据移到新的 Amazon 区域并希望在新区域中使用 KMS 密钥来加密数据密钥时,可以使用 Encypt 方法。

导入

require 'vendor/autoload.php'; use Aws\Exception\AwsException;

示例代码

$KmsClient = new Aws\Kms\KmsClient([ 'profile' => 'default', 'version' => '2014-11-01', 'region' => 'us-east-2' ]); $keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'; $message = pack('c*', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0); try { $result = $KmsClient->encrypt([ 'KeyId' => $keyId, 'Plaintext' => $message, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails echo $e->getMessage(); echo "\n"; }

Decrypt

要解密数据密钥,请使用 Decrypt 操作。

您指定的 ciphertextBlob 必须为 GenerateDataKeyGenerateDataKeyWithoutPlaintextEncrypt 响应中 CiphertextBlob 字段的值。

导入

require 'vendor/autoload.php'; use Aws\Exception\AwsException;

示例代码

$KmsClient = new Aws\Kms\KmsClient([ 'profile' => 'default', 'version' => '2014-11-01', 'region' => 'us-east-2' ]); $ciphertext = 'Place your cipher text blob here'; try { $result = $KmsClient->decrypt([ 'CiphertextBlob' => $ciphertext, ]); $plaintext = $result['Plaintext']; var_dump($plaintext); } catch (AwsException $e) { // Output error message if fails echo $e->getMessage(); echo "\n"; }

重新加密

要解密已加密数据密钥,然后立即在其他 KMS 密钥下重新加密该数据密钥,请使用 ReEncrypt 操作。这些操作全部都在 Amazon KMS 内的服务器端执行,因此它们永远不会将您的明文在 Amazon KMS 外公开。

您指定的 ciphertextBlob 必须为 GenerateDataKeyGenerateDataKeyWithoutPlaintextEncrypt 响应中 CiphertextBlob 字段的值。

导入

require 'vendor/autoload.php'; use Aws\Exception\AwsException;

示例代码

$KmsClient = new Aws\Kms\KmsClient([ 'profile' => 'default', 'version' => '2014-11-01', 'region' => 'us-east-2' ]); $keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'; $ciphertextBlob = 'Place your cipher text blob here'; try { $result = $KmsClient->reEncrypt([ 'CiphertextBlob' => $ciphertextBlob, 'DestinationKeyId' => $keyId, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails echo $e->getMessage(); echo "\n"; }