搭配 Amazon SQS 佇列使用伺服器端加密 - Amazon Simple Queue Service

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

搭配 Amazon SQS 佇列使用伺服器端加密

您可以使用 AWS SDK for Java 將伺服器端加密 (SSE) 新增至 Amazon SQS 佇列。每個佇列都使用 AWS Key Management Service (AWS KMS) KMS 金鑰來產生資料加密金鑰。此範例使用 Amazon SQS 的 AWS 受管 KMS 金鑰。如需使用 SSE 和 KMS 金鑰之角色的相關資訊,請參閱 Amazon 中的靜態加密 SQS

將 SSE 新增到現有佇列

若要啟用現有佇列的伺服器端加密,請使用 SetQueueAttributes 方法來設定 KmsMasterKeyId 屬性。

下列程式碼範例會將設定 AWS KMS key 為 Amazon SQS 的 AWS 受管 KMS 金鑰。此範例也會將 AWS KMS key 重複使用期間設定為 140 秒。

在執行範例程式碼之前,請確定您已設定 AWS 認證。如需詳細資訊,請參閱開發AWS SDK for Java 2.x 人員指南中的設定 AWS 認證和開發區域

// Create an SqsClient for the specified Region. SqsClient sqsClient = SqsClient.builder().region(Region.US_WEST_1).build(); // Get the URL of your queue. String myQueueName = "my queue"; GetQueueUrlResponse getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder().queueName(myQueueName).build()); String queueUrl = getQueueUrlResponse.queueUrl(); // Create a hashmap for the attributes. Add the key alias and reuse period to the hashmap. HashMap<QueueAttributeName, String> attributes = new HashMap<QueueAttributeName, String>(); final String kmsMasterKeyAlias = "alias/aws/sqs"; // the alias of the AWS managed KMS key for Amazon SQS. attributes.put(QueueAttributeName.KMS_MASTER_KEY_ID, kmsMasterKeyAlias); attributes.put(QueueAttributeName.KMS_DATA_KEY_REUSE_PERIOD_SECONDS, "140"); // Create the SetQueueAttributesRequest. SetQueueAttributesRequest set_attrs_request = SetQueueAttributesRequest.builder() .queueUrl(queueUrl) .attributes(attributes) .build(); sqsClient.setQueueAttributes(set_attrs_request);

停用佇列的 SSE

若要停用現有佇列的伺服器端加密,請使用 SetQueueAttributes 方法將 KmsMasterKeyId 屬性設定為空白字串。

重要

null 不是 KmsMasterKeyId 的有效值。

使用 SSE 建立佇列

若要在建立佇列時啟用 SSE,請將 KmsMasterKeyId 屬性新增至 CreateQueue API 方法。

以下範例顯示如何建立啟用 SSE 的新佇列。佇列使用 Amazon SQS 的 AWS 受管 KMS 金鑰。此範例也會將 AWS KMS key 重複使用期間設定為 160 秒。

在執行範例程式碼之前,請確定您已設定 AWS 認證。如需詳細資訊,請參閱開發AWS SDK for Java 2.x 人員指南中的設定 AWS 認證和開發區域

// Create an SqsClient for the specified Region. SqsClient sqsClient = SqsClient.builder().region(Region.US_WEST_1).build(); // Create a hashmap for the attributes. Add the key alias and reuse period to the hashmap. HashMap<QueueAttributeName, String> attributes = new HashMap<QueueAttributeName, String>(); final String kmsMasterKeyAlias = "alias/aws/sqs"; // the alias of the AWS managed KMS key for Amazon SQS. attributes.put(QueueAttributeName.KMS_MASTER_KEY_ID, kmsMasterKeyAlias); attributes.put(QueueAttributeName.KMS_DATA_KEY_REUSE_PERIOD_SECONDS, "140"); // Add the attributes to the CreateQueueRequest. CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .attributes(attributes) .build(); sqsClient.createQueue(createQueueRequest);

擷取 SSE 屬性

如需擷取佇列屬性的相關資訊,請參閱《Amazon Simple Queue Service API 參考》中的範例

若要擷取特定佇列的 KMS 金鑰 ID 或資料金鑰重複使用期間,請執行 GetQueueAttributes 方法並擷取 KmsMasterKeyIdKmsDataKeyReusePeriodSeconds 值。