CreateGrant搭配使用 AWS SDK或 CLI - AWS Key Management Service

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

CreateGrant搭配使用 AWS SDK或 CLI

以下代码示例演示如何使用 CreateGrant

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 AWS 代码示例存储库

public static async Task Main() { var client = new AmazonKeyManagementServiceClient(); // The identity that is given permission to perform the operations // specified in the grant. var grantee = "arn:aws:iam::111122223333:role/ExampleRole"; // The identifier of the AWS KMS key to which the grant applies. You // can use the key ID or the Amazon Resource Name (ARN) of the KMS key. var keyId = "7c9eccc2-38cb-4c4f-9db3-766ee8dd3ad4"; var request = new CreateGrantRequest { GranteePrincipal = grantee, KeyId = keyId, // A list of operations that the grant allows. Operations = new List<string> { "Encrypt", "Decrypt", }, }; var response = await client.CreateGrantAsync(request); string grantId = response.GrantId; // The unique identifier of the grant. string grantToken = response.GrantToken; // The grant token. Console.WriteLine($"Id: {grantId}, Token: {grantToken}"); } }
  • 有关API详细信息,请参阅CreateGrant中的 AWS SDK for .NET API参考

CLI
AWS CLI

创建授权

以下create-grant示例创建了一个授权,允许exampleUser用户在1234abcd-12ab-34cd-56ef-1234567890ab示例KMS密钥上使用该decrypt命令。停用主体是 adminRole 角色。该授权使用 EncryptionContextSubset 授权约束,以便仅在 decrypt 请求中的加密上下文包含 "Department": "IT" 键值对时才允许此权限。

aws kms create-grant \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --grantee-principal arn:aws:iam::123456789012:user/exampleUser \ --operations Decrypt \ --constraints EncryptionContextSubset={Department=IT} \ --retiring-principal arn:aws:iam::123456789012:role/adminRole

输出:

{ "GrantId": "1a2b3c4d2f5e69f440bae30eaec9570bb1fb7358824f9ddfa1aa5a0dab1a59b2", "GrantToken": "<grant token here>" }

要查看有关授权的详细信息,请使用 list-grants 命令。

有关更多信息,请参阅中的资助 AWS KMSAWS 密钥管理服务开发人员指南

  • 有关API详细信息,请参阅CreateGrant中的 AWS CLI 命令参考

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 AWS 代码示例存储库

/** * Grants permissions to a specified principal on a customer master key (CMK) asynchronously. * * @param keyId The unique identifier for the customer master key (CMK) that the grant applies to. * @param granteePrincipal The principal that is given permission to perform the operations that the grant permits on the CMK. * @return A {@link CompletableFuture} that, when completed, contains the ID of the created grant. * @throws RuntimeException If an error occurs during the grant creation process. */ public CompletableFuture<String> grantKeyAsync(String keyId, String granteePrincipal) { List<GrantOperation> grantPermissions = List.of( GrantOperation.ENCRYPT, GrantOperation.DECRYPT, GrantOperation.DESCRIBE_KEY ); CreateGrantRequest grantRequest = CreateGrantRequest.builder() .keyId(keyId) .name("grant1") .granteePrincipal(granteePrincipal) .operations(grantPermissions) .build(); CompletableFuture<CreateGrantResponse> responseFuture = getAsyncClient().createGrant(grantRequest); responseFuture.whenComplete((response, ex) -> { if (ex == null) { logger.info("Grant created successfully with ID: " + response.grantId()); } else { if (ex instanceof KmsException kmsEx) { throw new RuntimeException("Failed to create grant: " + kmsEx.getMessage(), kmsEx); } else { throw new RuntimeException("An unexpected error occurred: " + ex.getMessage(), ex); } } }); return responseFuture.thenApply(CreateGrantResponse::grantId); }
  • 有关API详细信息,请参阅CreateGrant中的 AWS SDK for Java 2.x API参考

Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 AWS 代码示例存储库

suspend fun createNewGrant( keyIdVal: String?, granteePrincipalVal: String?, operation: String, ): String? { val operationOb = GrantOperation.fromValue(operation) val grantOperationList = ArrayList<GrantOperation>() grantOperationList.add(operationOb) val request = CreateGrantRequest { keyId = keyIdVal granteePrincipal = granteePrincipalVal operations = grantOperationList } KmsClient { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.createGrant(request) return response.grantId } }
  • 有关API详细信息,请参阅CreateGrant中的 AWS SDK以供API参考 Kotlin。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 AWS 代码示例存储库

class GrantManager: def __init__(self, kms_client): self.kms_client = kms_client def create_grant(self, key_id): """ Creates a grant for a key that lets a principal generate a symmetric data encryption key. :param key_id: The ARN or ID of the key. :return: The grant that is created. """ principal = input( f"Enter the ARN of a principal, such as an IAM role, to grant that role " f"GenerateDataKey permissions on key {key_id}: " ) if principal != "": try: grant = self.kms_client.create_grant( KeyId=key_id, GranteePrincipal=principal, Operations=["GenerateDataKey"], ) except ClientError as err: logger.error( "Couldn't create a grant on key %s. Here's why: %s", key_id, err.response["Error"]["Message"], ) else: print(f"Grant created on key {key_id}.") return grant else: print("Skipping grant creation.")
  • 有关API详细信息,请参阅CreateGrant中的 AWS SDK供参考 Python (Boto3) API。

有关完整列表 AWS SDK开发者指南和代码示例,请参阅使用 AWS KMS 用一个 AWS SDK。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。