使用 适用于 PHP 的 AWS SDK 版本 3 来加密和解密 AWS KMS 数据密钥
数据密钥是可用于加密数据的加密密钥,包括大量数据和其他数据加密密钥。
可以使用 AWS Key Management Service 的 (AWS KMS) AWS KMS key 来生成、加密和解密数据密钥。
以下示例演示如何:
适用于 PHP 的 AWS SDKGitHub 上提供了
凭证
运行示例代码之前,请配置您的 AWS 凭证,如 通过适用于 PHP 的 AWS SDK 版本 3 使用 AWS 进行身份验证 中所述。然后导入 适用于 PHP 的 AWS SDK,如 安装适用于 PHP 的 AWS SDK 版本 3 中所述。
有关使用 AWS Key Management Service (AWS KMS) 的更多信息,请参阅 AWS KMS 开发人员指南。
Encrypt
Encrypt 操作专用于加密数据密钥,但并不常用。GenerateDataKey 和 GenerateDataKeyWithoutPlaintext 操作会返回加密的数据密钥。将加密的数据移到新的 AWS 区域并希望在新区域中使用 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 必须为 GenerateDataKey、GenerateDataKeyWithoutPlaintext 或 Encrypt 响应中 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 操作。这些操作全部都在 AWS KMS 内的服务器端执行,因此它们永远不会将您的明文在 AWS KMS 外公开。
您指定的 ciphertextBlob 必须为 GenerateDataKey、GenerateDataKeyWithoutPlaintext 或 Encrypt 响应中 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"; }