PutBucketEncryption 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

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

PutBucketEncryption 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 PutBucketEncryption

.NET
AWS SDK for .NET
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// Set the bucket server side encryption to use AWSKMS with a customer-managed key id. /// </summary> /// <param name="bucketName">Name of the bucket.</param> /// <param name="kmsKeyId">The Id of the KMS Key.</param> /// <returns>True if successful.</returns> public static async Task<bool> SetBucketServerSideEncryption(string bucketName, string kmsKeyId) { var serverSideEncryptionByDefault = new ServerSideEncryptionConfiguration { ServerSideEncryptionRules = new List<ServerSideEncryptionRule> { new ServerSideEncryptionRule { ServerSideEncryptionByDefault = new ServerSideEncryptionByDefault { ServerSideEncryptionAlgorithm = ServerSideEncryptionMethod.AWSKMS, ServerSideEncryptionKeyManagementServiceKeyId = kmsKeyId } } } }; try { var encryptionResponse = await _s3Client.PutBucketEncryptionAsync(new PutBucketEncryptionRequest { BucketName = bucketName, ServerSideEncryptionConfiguration = serverSideEncryptionByDefault, }); return encryptionResponse.HttpStatusCode == HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine(ex.ErrorCode == "AccessDenied" ? $"This account does not have permission to set encryption on {bucketName}, please try again." : $"Unable to set bucket encryption for bucket {bucketName}, {ex.Message}"); } return false; }
CLI
AWS CLI

設定儲存貯體的伺服器端加密

下列put-bucket-encryption範例會將 AES256 加密設定為指定儲存貯體的預設值。

aws s3api put-bucket-encryption \ --bucket my-bucket \ --server-side-encryption-configuration '{"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]}'

此命令不會產生輸出。

PowerShell
for PowerShell 工具

範例 1:此命令會在指定的儲存貯體上使用 Amazon S3 受管金鑰 (Word-S3) 啟用預設 SSE AES256 伺服器端加密。

$Encryptionconfig = @{ServerSideEncryptionByDefault = @{ServerSideEncryptionAlgorithm = "AES256"}} Set-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket' -ServerSideEncryptionConfiguration_ServerSideEncryptionRule $Encryptionconfig
  • 如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 PutBucketEncryption