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

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

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

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

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

以下示例演示如何:

  • 使用 Encrypt 加密数据密钥。

  • 使用 Decrypt 解密数据密钥。

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

的所有示例代码都可以在此Amazon SDK for PHP处找到 GitHub

凭证

运行示例代码之前,请配置您的 Amazon 凭证,如 凭证 中所述。然后导入 Amazon SDK for PHP,如 基本用法 中所述。

有关使用 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 操作。

您指定的必须ciphertextBlobGenerateDataKeyGenerateDataKeyWithoutPlaintext或 E ncrypt 响应中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 外公开。

您指定的必须ciphertextBlobGenerateDataKeyGenerateDataKeyWithoutPlaintext或 E ncrypt 响应中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"; }