

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# AWS Key Management Service 使用第 3 適用於 PHP 的 AWS SDK 版的範例
<a name="kms-examples"></a>

AWS Key Management Service (AWS KMS) 是一種受管服務，可讓您輕鬆建立和控制用來加密資料的加密金鑰。如需 的詳細資訊 AWS KMS，請參閱 [Amazon KMS 文件](https://aws.amazon.com/documentation/kms/)。無論您是撰寫安全的 PHP 應用程式，還是將資料傳送到其他 AWS 服務， 都 AWS KMS 可協助您維持對誰可以使用您的金鑰的控制權，並存取您的加密資料。

第 3 適用於 PHP 的 AWS SDK 版的所有範例程式碼都可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)。

**Topics**
+ [處理金鑰](kms-example-keys.md)
+ [加密和解密資料金鑰](kms-example-encrypt.md)
+ [處理金鑰政策](kms-example-key-policy.md)
+ [使用授與](kms-example-grants.md)
+ [處理別名](kms-example-alias.md)

# 使用 AWS KMS API 和 第 3 適用於 PHP 的 AWS SDK 版使用金鑰
<a name="kms-example-keys"></a>

 AWS Key Management Service (AWS KMS) 中的主要資源為 [AWS KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)。您可以使用 KMS 金鑰來加密您的資料。

下列範例示範如何：
+ 使用 [CreateKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#createkey) 建立客戶 KMS 金鑰。
+ 使用 [GenerateDataKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#generatedatakey) 產生資料金鑰。
+ 使用 [DescribeKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#describekey) 檢視 KMS 金鑰。
+ 使用 [ListKeys](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#listkeys) 取得 KMS 金鑰的金鑰 IDs 和金鑰 ARNS。
+ 使用 [EnableKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#enablekey) 啟用 KMS 金鑰。
+ 使用 [DisableKey](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#disablekey) 停用 KMS 金鑰。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

如需使用 AWS Key Management Service (AWS KMS) 的詳細資訊，請參閱 [AWS KMS 開發人員指南](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 建立 KMS 金鑰
<a name="create-a-cmk"></a>

若要建立 [KMS 金鑰](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)，請使用 [CreateKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html) 操作。

 **匯入** 

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
```

 **範例程式碼** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

//Creates a customer master key (CMK) in the caller's AWS account.
$desc = "Key for protecting critical data";

try {
    $result = $KmsClient->createKey([
        'Description' => $desc,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 產生資料金鑰
<a name="generate-a-data-key"></a>

若要產生資料加密金鑰，請使用 [GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html) 操作。這個操作會傳回它建立的純文字和加密的資料金鑰副本。指定要在 AWS KMS key 其中產生資料金鑰的 。

 **匯入** 

```
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';
$keySpec = 'AES_256';

try {
    $result = $KmsClient->generateDataKey([
        'KeyId' => $keyId,
        'KeySpec' => $keySpec,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 檢視 KMS 金鑰
<a name="view-a-cmk"></a>

若要取得 KMS 金鑰的詳細資訊，包括 KMS 金鑰的 Amazon Resource Name (ARN) 和[金鑰狀態](https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html)，請使用 [DescribeKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html) 操作。

 `DescribeKey` 不會取得別名。若要取得別名，請使用 [ListAliases](https://docs.aws.amazon.com/kms/latest/APIReference/API_ListKeys.html) 操作。

 **匯入** 

```
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';

try {
    $result = $KmsClient->describeKey([
        'KeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 取得 KMS 金鑰的金鑰 ARNs
<a name="get-the-key-id-and-key-arns-of-a-cmk"></a>

若要取得 KMS 金鑰的 ID 和 ARN，請使用 [ListAliases](https://docs.aws.amazon.com/kms/latest/APIReference/API_ListKeys.html) 操作。

 **匯入** 

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
```

 **範例程式碼** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$limit = 10;

try {
    $result = $KmsClient->listKeys([
        'Limit' => $limit,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 啟用 KMS 金鑰
<a name="enable-a-cmk"></a>

若要啟用已停用的 KMS 金鑰，請使用 [EnableKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_EnableKey.html) 操作。

 **匯入** 

```
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';

try {
    $result = $KmsClient->enableKey([
        'KeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 停用 KMS 金鑰
<a name="disable-a-cmk"></a>

若要停用 KMS 金鑰，請使用 [DisableKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_DisableKey.html) 操作。停用 KMS 金鑰可防止其被使用。

 **匯入** 

```
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';

try {
    $result = $KmsClient->disableKey([
        'KeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版加密和解密 AWS KMS 資料金鑰
<a name="kms-example-encrypt"></a>

資料金鑰是加密金鑰，您可以用來加密資料，包括大量資料和其他資料加密金鑰。

您可以使用 AWS Key Management Service的 (AWS KMS) [AWS KMS key](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)來產生、加密和解密資料金鑰。

下列範例示範如何：
+ 使用 [Encrypt](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#encrypt) 加密資料金鑰。
+ 使用 [Decrypt](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#decrypt) 解密資料金鑰。
+ 使用 [ReEncrypt](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#reencrypt) 以新的 KMS 金鑰重新加密資料金鑰。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

如需使用 AWS Key Management Service (AWS KMS) 的詳細資訊，請參閱 [AWS KMS 開發人員指南](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 加密
<a name="encrypt"></a>

[Encrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) 操作旨在加密資料金鑰，但並不常用。[GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html) 和 [GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html) 操作會傳回加密的資料金鑰。當您將加密的資料移至新 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";
}
```

## 解密
<a name="decrypt"></a>

若要解密資料金鑰，請使用 [Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) 操作。

`ciphertextBlob` 您指定的 必須是 [GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html)、[GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html) 或 [Encrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) 回應中 `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";
}
```

## 重新加密
<a name="reencrypt"></a>

若要解密加密的資料金鑰，然後在不同的 KMS 金鑰下立即重新加密資料金鑰，請使用 [ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html) 操作。這些操作完全在內部的伺服器端執行 AWS KMS，因此絕不會在外部公開您的純文字 AWS KMS。

`ciphertextBlob` 您指定的 必須是 [GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html)、[GenerateDataKeyWithoutPlaintext](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKeyWithoutPlaintext.html) 或 [Encrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) 回應中 `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";
}
```

# 使用第 3 適用於 PHP 的 AWS SDK 版使用 AWS KMS 金鑰政策
<a name="kms-example-key-policy"></a>

建立 時[AWS KMS key](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)，您可以判斷誰可以使用和管理該 KMS 金鑰。這些許可包含在稱為金鑰政策的文件中。您可以隨時使用金鑰政策來新增、移除或修改客戶受管 KMS 金鑰的許可，但您無法編輯 AWS 受管 KMS 金鑰的金鑰政策。如需詳細資訊，請參閱 [的身分驗證和存取控制 AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/control-access.html)。

下列範例示範如何：
+ 使用 [ListKeyPolicies](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#listkeypolicies) 列出金鑰政策的名稱。
+ 使用 [GetKeyPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#getkeypolicy) 取得金鑰政策。
+ 使用 [PutKeyPolicy](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#putkeypolicy) 設定金鑰政策。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

如需使用 AWS Key Management Service (AWS KMS) 的詳細資訊，請參閱 [AWS KMS 開發人員指南](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 列出所有金鑰政策
<a name="list-all-key-policies"></a>

若要取得 KMS 金鑰的金鑰政策名稱，請使用 `ListKeyPolicies`操作。

 **匯入** 

```
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';
$limit = 10;

try {
    $result = $KmsClient->listKeyPolicies([
        'KeyId' => $keyId,
        'Limit' => $limit,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 擷取金鑰政策
<a name="retrieve-a-key-policy"></a>

若要取得 KMS 金鑰的金鑰政策，請使用 `GetKeyPolicy`操作。

 `GetKeyPolicy` 需要政策名稱。除非您在建立 KMS 金鑰時建立金鑰政策，否則唯一的有效政策名稱為預設值。進一步了解《 *AWS Key Management Service 開發人員指南*》中的[預設金鑰政策](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html)。

 **匯入** 

```
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';
$policyName = "default";

try {
    $result = $KmsClient->getKeyPolicy([
        'KeyId' => $keyId,
        'PolicyName' => $policyName
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 設定金鑰政策
<a name="set-a-key-policy"></a>

若要建立或變更 KMS 金鑰的金鑰政策，請使用 `PutKeyPolicy`操作。

 `PutKeyPolicy` 需要政策名稱。除非您在建立 KMS 金鑰時建立金鑰政策，否則唯一的有效政策名稱為預設值。進一步了解《 *AWS Key Management Service 開發人員指南*》中的[預設金鑰政策](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html)。

 **匯入** 

```
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';
$policyName = "default";

try {
    $result = $KmsClient->putKeyPolicy([
        'KeyId' => $keyId,
        'PolicyName' => $policyName,
        'Policy' => '{ 
            "Version":"2012-10-17",		 	 	  
            "Id": "custom-policy-2016-12-07", 
            "Statement": [ 
                { "Sid": "Enable IAM User Permissions", 
                "Effect": "Allow", 
                "Principal": 
                   { "AWS": "arn:aws:iam::111122223333:user/root" }, 
                "Action": [ "kms:*" ], 
                "Resource": "*" }, 
                { "Sid": "Enable IAM User Permissions", 
                "Effect": "Allow", 
                "Principal":                 
                   { "AWS": "arn:aws:iam::111122223333:user/ExampleUser" }, 
                "Action": [
                    "kms:Encrypt*",
                    "kms:GenerateDataKey*",
                    "kms:Decrypt*",
                    "kms:DescribeKey*",
                    "kms:ReEncrypt*"
                ], 
                "Resource": "*" }                 
            ]            
        } '
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 AWS KMS API 和 第 3 適用於 PHP 的 AWS SDK 版使用授予
<a name="kms-example-grants"></a>

授與是提供許可的另一個機制。這是金鑰政策的替代方案。您可以使用授予來提供長期存取權，讓 AWS 主體使用您的 AWS Key Management Service (AWS KMS) 客戶受管 [AWS KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)。如需詳細資訊，請參閱《 *AWS Key Management Service 開發人員指南*[》中的在 中授予 AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html)。

下列範例示範如何：
+ 使用 [CreateGrant](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#creategrant) 建立 KMS 金鑰的授予。
+ 使用 [ListGrants](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#listgrants) 檢視 KMS 金鑰的授予。
+ 使用 [RetireGrant](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#retiregrant) 淘汰 KMS 金鑰的授予。
+ 使用 RevokeGrant 撤銷 KMS [RevokeGrant](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#revokegrant)。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

如需使用 AWS Key Management Service (AWS KMS) 的詳細資訊，請參閱 [AWS KMS 開發人員指南](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 建立授與
<a name="create-a-grant"></a>

若要建立 的授予 AWS KMS key，請使用 [CreateGrant](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateGrant.html) 操作。

 **匯入** 

```
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';
$granteePrincipal = "arn:aws:iam::111122223333:user/Alice";
$operation = ['Encrypt', 'Decrypt']; // A list of operations that the grant allows.

try {
    $result = $KmsClient->createGrant([
        'GranteePrincipal' => $granteePrincipal,
        'KeyId' => $keyId,
        'Operations' => $operation
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 檢視授權
<a name="view-a-grant"></a>

若要取得 上授予的詳細資訊 AWS KMS key，請使用 [ListGrants](https://docs.aws.amazon.com/kms/latest/APIReference/API_ListGrants.html) 操作。

 **匯入** 

```
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';
$limit = 10;

try {
    $result = $KmsClient->listGrants([
        'KeyId' => $keyId,
        'Limit' => $limit,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 淘汰授予
<a name="retire-a-grant"></a>

若要淘汰 的授予 AWS KMS key，請使用 [RetireGrant](https://docs.aws.amazon.com/kms/latest/APIReference/API_RetireGrant.html) 操作。授予使用完畢後，將其淘汰以進行清理。

 **匯入** 

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
```

 **範例程式碼** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$grantToken = 'Place your grant token here';

try {
    $result = $KmsClient->retireGrant([
        'GrantToken' => $grantToken,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}

//Can also identify grant to retire by a combination of the grant ID
//and the Amazon Resource Name (ARN) of the customer master key (CMK)
$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$grantId = 'Unique identifier of the grant returned during CreateGrant operation';

try {
    $result = $KmsClient->retireGrant([
        'GrantId' => $grantToken,
        'KeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 撤銷授予
<a name="revoke-a-grant"></a>

若要撤銷對 的授予 AWS KMS key，請使用 [RevokeGrant](https://docs.aws.amazon.com/kms/latest/APIReference/API_RevokeGrant.html) 操作。您可以撤銷授與以明確拒絕依賴它的操作。

 **匯入** 

```
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';
$grantId = "grant1";

try {
    $result = $KmsClient->revokeGrant([
        'KeyId' => $keyId,
        'GrantId' => $grantId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

# 使用 AWS KMS API 和 第 3 適用於 PHP 的 AWS SDK 版使用別名
<a name="kms-example-alias"></a>

AWS Key Management Service (AWS KMS) 為[AWS KMS key](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys)稱為別名的 提供選用的顯示名稱。

下列範例示範如何：
+ 使用 [CreateAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#createalias) 建立別名。
+ 使用 [ListAliases](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#listaliases) 檢視別名。
+ 使用 [UpdateAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#updatealias) 更新別名。
+ 使用 [DeleteAlias](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-kms-2014-11-01.html#deletealias) 刪除別名。

您可以在 GitHub 上 適用於 PHP 的 AWS SDK 取得 的所有範例程式碼。 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code)

## 憑證
<a name="examplecredentials"></a>

在執行範例程式碼之前，請先設定您的 AWS 登入資料，如中所述[AWS 使用第 3 適用於 PHP 的 AWS SDK 版向 驗證](credentials.md)。然後匯入 適用於 PHP 的 AWS SDK，如 中所述[安裝第 3 適用於 PHP 的 AWS SDK 版](getting-started_installation.md)。

如需使用 AWS Key Management Service (AWS KMS) 的詳細資訊，請參閱 [AWS KMS 開發人員指南](https://docs.aws.amazon.com/kms/latest/developerguide/)。

## 建立別名
<a name="create-an-alias"></a>

若要建立 KMS 金鑰的別名，請使用 [CreateAlias](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateAlias.html) 操作。別名在帳戶和 AWS 區域中必須是唯一的。如果您為已有別名的 KMS 金鑰建立別名， 會為相同的 KMS 金鑰`CreateAlias`建立另一個別名。其並不會取代現有的別名。

 **匯入** 

```
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';
$aliasName = "alias/projectKey1";

try {
    $result = $KmsClient->createAlias([
        'AliasName' => $aliasName,
        'TargetKeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 檢視別名
<a name="view-an-alias"></a>

若要列出呼叫者 AWS 帳戶 和 中的所有別名 AWS 區域，請使用 [ListAliases](https://docs.aws.amazon.com/kms/latest/APIReference/API_ListAliases.html) 操作。

 **匯入** 

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
```

 **範例程式碼** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$limit = 10;

try {
    $result = $KmsClient->listAliases([
        'Limit' => $limit,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 更新別名
<a name="update-an-alias"></a>

若要將現有的別名關聯至不同的 KMS 金鑰，請使用 [UpdateAlias](https://docs.aws.amazon.com/kms/latest/APIReference/API_UpdateAlias.html) 操作。

 **匯入** 

```
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';
$aliasName = "alias/projectKey1";

try {
    $result = $KmsClient->updateAlias([
        'AliasName' => $aliasName,
        'TargetKeyId' => $keyId,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```

## 刪除別名
<a name="delete-an-alias"></a>

若要刪除別名，請使用 [DeleteAlias](https://docs.aws.amazon.com/kms/latest/APIReference/API_DeleteAlias.html) 操作。刪除別名不會影響基礎 KMS 金鑰。

 **匯入** 

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
```

 **範例程式碼** 

```
$KmsClient = new Aws\Kms\KmsClient([
    'profile' => 'default',
    'version' => '2014-11-01',
    'region' => 'us-east-2'
]);

$aliasName = "alias/projectKey1";

try {
    $result = $KmsClient->deleteAlias([
        'AliasName' => $aliasName,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}
```