Ask Your Question
4

What is the process for encrypting AWS S3 objects using KMS - CMK from Lambda in .Net?

asked 2023-05-13 16:02:52 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-13 16:24:01 +0000

bukephalos gravatar image

Here is the process to encrypt AWS S3 objects using KMS - CMK from Lambda in .Net:

  1. Create a KMS - CMK key in AWS console or using AWS SDK.

  2. Create an S3 bucket or use an existing bucket.

  3. Create a Lambda function using AWS Console or using the AWS SDK.

  4. Configure the Lambda function to access the S3 bucket and KMS - CMK.

  5. Write the Lambda function code to encrypt the S3 object using KMS.

  6. Test the Lambda function by executing it.

  7. Verify that the Lambda function has encrypted the S3 object using KMS - CMK.

Code example:

public static async Task<GetObjectResponse> GetS3Object(string key)
{
    using (var s3Client = new AmazonS3Client())
    {
        var request = new GetObjectRequest
        {
            BucketName = "my-bucket",
            Key = key
        };

        var response = await s3Client.GetObjectAsync(request);

        return response;
    }
}

public static async Task<PutObjectResponse> PutS3Object(string key, string body)
{
    using (var s3Client = new AmazonS3Client())
    using (var kmsClient = new AmazonKeyManagementServiceClient())
    {
        var kmsRequest = new GenerateDataKeyRequest
        {
            KeyId = "my-kms-key-id",
            KeySpec = DataKeySpec.AES_256
        };

        var kmsResponse = await kmsClient.GenerateDataKeyAsync(kmsRequest);

        var request = new PutObjectRequest
        {
            BucketName = "my-bucket",
            Key = key,
            InputStream = new MemoryStream(Encoding.UTF8.GetBytes(body)),
            ServerSideEncryptionMethod = ServerSideEncryptionMethod.AwsKms,
            ServerSideEncryptionKeyManagementServiceKeyId = kmsResponse.KeyId
        };

        var response = await s3Client.PutObjectAsync(request);

        return response;
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-13 16:02:52 +0000

Seen: 9 times

Last updated: May 13 '23