Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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;
    }
}