DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Monitoring and Logging in Cloud Architecture With Python
  • The Essentials of Amazon S3 Glacier for Affordable and Compliant Long-Term Data Archiving
  • Microservices With Apache Camel and Quarkus (Part 4)
  • Building a RAG-Powered Bug Triage Agent With AWS Bedrock and OpenSearch k-NN

Trending

  • Building a Skill-Based Agentic Reviewer with Claude Code: A Practical Guide Using Skills.MD, MCP Servers, Tools, and Tasks
  • The Middleware Gap in AI Agent Frameworks
  • Evolving Spring Boot APIs to an Event-Driven Mesh
  • MuleSoft MCP and A2A in Production: What 17 Recipes Reveal
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. AWS S3 Client-side Encryption in AWS SDK .NET Core

AWS S3 Client-side Encryption in AWS SDK .NET Core

The advantage of client-side encryption is, encryption is performed locally, and the data never leaves the execution environment unencrypted.

By 
Chandra Kudumula user avatar
Chandra Kudumula
·
May. 07, 21 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
10.0K Views

Join the DZone community and get the full member experience.

Join For Free

AWS S3 Client-side Encryption in AWS SDK .NET Core

When you upload the data into the S3 bucket, you need to ensure that the sensitive data is secure by using proper encryption. Amazon S3 allows encrypting the data or objects either on the server-side or client-side.

Here, I will use client-side encryption for data before sending it to Amazon S3 using AWS SDK .Net Core. The advantage of client-side encryption is, encryption is performed locally, and the data never leaves the execution environment unencrypted. Another advantage is you can use your master keys for encryption, and no one can access your data without having your master encryption keys.

Prerequisites

  • Visual Studio 2017 or above. You can download the latest here.
  • AWS account. You can create the account here.

Steps Overview

  1. Create IAM (Identity and Access Management) user.
  2. Create Console App in Visual Studio 2019 and install AWS Toolkit.
  3. Code to encrypt the data, save it into Amazon S3 and decrypt the data before reading.

Execution

1. Create an IAM (Identity and Access Management) user and use the user's credentials in AWS SDK. After login into AWS, type IAM in the search bar and select IAM.Create an IAM

On the IAM Dashboard, select the 'Users' and click on 'Add user'

IAM Dashboard > Add Users

Provide the required info and click on 'Next: Permissions'

Configure User Details

On the Permissions window, Attach the AmazonS3FullAccess to the user and click on 'Tags' -> 'Review' -> 'Create user.'

Attach Existing Policies Directly

After the user is created, either download the .csv file or make a note of Access Key ID and Secret access key, and we will use them in visual studio to connect to the Amazon S3.

Successful User Creation

2. Open the Visual Studio and create a new Console Application.

Create New Project

Provide the project name and click on 'Next' and select the Target Framework (In VS 2019, I choose .NET 5.0).Configure New Project

Set up the AWS Toolkit for Visual Studio by following the instructions here.

After AWS Toolkit is installed, open the 'AWS Explorer' from the 'View' menu bar in Visual Studio.

View > AWS Explorer

You can enter the credentials (Access Key ID and Secret Access Key) OR import the CSV file created in step 1 and click on 'OK.'

New Account Profile Configuration

After AWS Toolkit makes the successful connection, AWS Explorer looks like below.

AWS Explorer > Amazon S3

Install the NuGet packages 'AWSSDK.S3' and 'Amazon.Extensions.S3.Encryption' to the console project.

Dependencies > Packages

Provide the bucket name and object name as the application arguments. The arguments should be separated by a space.

Application Arguments

3. Write the code in the program.cs file.

Using the 'AmazonS3EncryptionClientV2' class, the SDK automatically encrypts data on the client when uploading to Amazon S3 and automatically decrypts it when the data is retrieved.

In AWS, the entire process of encryption and decryption is called 'envelope encryption.' You can read more about this here.

Below is the complete code in the program.cs file:

C#
 




x
72


 
1
using System;
2
using System.IO;
3
using System.Security.Cryptography;
4
using System.Threading.Tasks;
5
using Amazon.Extensions.S3.Encryption;
6
using Amazon.Extensions.S3.Encryption.Primitives;
7
using Amazon.S3.Model;
8

          
9
namespace S3ClientSideEncryptionDemo
10
{
11
    class Program
12
    {
13
        static async Task Main(string[] args)
14
        {
15
            //EncryptionMaterialsV2 object that holds an instance of either an asymmetric algorithm (preferably RSA) or a symmetric algorithm.
16
            var encryptionMaterials = new EncryptionMaterialsV2(RSA.Create(), AsymmetricAlgorithmType.RsaOaepSha1);
17

          
18
            // choose to store the key either in object metadata or in an instruction file.
19
            var config = new AmazonS3CryptoConfigurationV2(SecurityProfile.V2AndLegacy)
20
            {
21
                StorageMode = CryptoStorageMode.ObjectMetadata
22
            };
23

          
24
            //AmazonS3EncryptionClientV2 class, the SDK automatically encrypts data on the client when uploading to Amazon S3, and automatically decrypts it when data is retrieved.
25
            var s3EncClient = new AmazonS3EncryptionClientV2(config, encryptionMaterials);
26

          
27
            try
28
            {
29
                //bucket name
30
                var bucketName = args[0];
31

          
32
                //identify object in the Amazon S3
33
                var key = args[1];
34

          
35
                //Create the Bucket
36
                Console.WriteLine($"\nCreating bucket {bucketName}...");
37
                var createBucketResponse = await s3EncClient.PutBucketAsync(bucketName);
38
                Console.WriteLine($"Result: {createBucketResponse.HttpStatusCode.ToString()}");
39

          
40
                // Create the object in the bucket
41
                var createObjResponse =
42
                    await s3EncClient.PutObjectAsync(new PutObjectRequest
43
                    {
44
                        BucketName = bucketName,
45
                        Key = key,
46
                        ContentBody = File.ReadAllText("C:\\data-to-store-in-s3.txt")
47
                    });
48
                Console.WriteLine($"Result: {createObjResponse.HttpStatusCode.ToString()}");
49

          
50
                //Retrieve the object from the bucket
51
                var getResponse =
52
                    await s3EncClient.GetObjectAsync(new GetObjectRequest
53
                    {
54
                        BucketName = bucketName,
55
                        Key = key
56
                    });
57

          
58
                //Display the message
59
                Stream stream = getResponse.ResponseStream;
60
                StreamReader reader = new StreamReader(stream);
61
                Console.WriteLine(reader.ReadToEnd());
62
                Console.ReadLine();
63
            }
64
            catch (Exception e)
65
            {
66
                Console.WriteLine("Caught exception when creating a bucket or placing an object in the bucket:");
67
                Console.WriteLine(e.Message);
68
            }
69
        }
70
    }
71
}
72

          



After running the code, the console window displays the message:

Console Window Message

Here we have seen how to encrypt the data on the client-side for Amazon S3 object using AWS SDK .NET Core console application.

AWS Software development kit Client-side encryption

Opinions expressed by DZone contributors are their own.

Related

  • Monitoring and Logging in Cloud Architecture With Python
  • The Essentials of Amazon S3 Glacier for Affordable and Compliant Long-Term Data Archiving
  • Microservices With Apache Camel and Quarkus (Part 4)
  • Building a RAG-Powered Bug Triage Agent With AWS Bedrock and OpenSearch k-NN

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook