AWS Code Sample
Catalog

Program.cs

AwsS3EncryptionClient sample demonstrates how to use the S3 encryption client to encrypt and decrypt data when using S3 operations.

//snippet-keyname:[Amazon Simple Storage Service] /******************************************************************************* * Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. *******************************************************************************/ using System; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Encryption; namespace GettingStartedGuide { class S3Sample { // Change the AWSProfileName to the profile you want to use in the App.config file. // See http://aws.amazon.com/credentials for more details. // You must also sign up for an Amazon S3 account for this to work // See http://aws.amazon.com/s3/ for details on creating an Amazon S3 account // Change the bucketName and keyName fields to values that match your bucketname and keyname static string bucketName; static string keyName; static string keyContainerName = "S3SampleKeyContainer"; static IAmazonS3 client; public static void Main(string[] args) { bucketName = args[0]; keyName = args[1]; if (checkRequiredFields()) { // Create a key container and RSA key in the container // You must have the key to be able to read data you created using the key RSACryptoServiceProvider rsaKey = new System.Security.Cryptography.RSACryptoServiceProvider(); CspParameters cp = new CspParameters(); cp.KeyContainerName = keyContainerName; RSACryptoServiceProvider key = new RSACryptoServiceProvider(cp); // Display the key information. Console.WriteLine("Key in container " + keyContainerName + ": \n {0}", key.ToXmlString(true)); using (client = new AmazonS3EncryptionClient(new EncryptionMaterials(key))) { Console.WriteLine("Listing buckets"); ListingBuckets(); Console.WriteLine("Creating a bucket"); CreateABucket(); Console.WriteLine("Writing an object"); WritingAnObject(); Console.WriteLine("Reading an object"); ReadingAnObject(); Console.WriteLine("Deleting an object"); DeletingAnObject(); Console.WriteLine("Listing objects"); ListingObjects(); } // Show the key used to write the data has been persisted CspParameters csp = new CspParameters(); cp.KeyContainerName = keyContainerName; // Create a new instance of RSACryptoServiceProvider that accesses the key container // keyContainerName. // If there is no key in the container one is created and stored. // If a key exists that key is used. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp); // Display the key information to the console. Console.WriteLine("Key persisted in container : \n {0}", key.ToXmlString(true)); // Delete the key in the container rsa.PersistKeyInCsp = false; // Delete the key from the container and release resources. rsa.Clear(); Console.WriteLine("Key deleted."); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } static bool checkRequiredFields() { NameValueCollection appConfig = ConfigurationManager.AppSettings; if (string.IsNullOrEmpty(appConfig["AWSProfileName"])) { Console.WriteLine("AWSProfileName was not set in the App.config file."); return false; } if (string.IsNullOrEmpty(bucketName)) { Console.WriteLine("The variable bucketName is not set."); return false; } if (string.IsNullOrEmpty(keyName)) { Console.WriteLine("The variable keyName is not set."); return false; } return true; } static void ListingBuckets() { try { ListBucketsResponse response = client.ListBuckets(); foreach (S3Bucket bucket in response.Buckets) { Console.WriteLine("You own Bucket with name: {0}", bucket.BucketName); } } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { Console.WriteLine("Please check the provided AWS Credentials."); Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3"); } else { Console.WriteLine("An Error, number {0}, occurred when listing buckets with the message '{1}", amazonS3Exception.ErrorCode, amazonS3Exception.Message); } } } static void CreateABucket() { try { PutBucketRequest request = new PutBucketRequest(); request.BucketName = bucketName; client.PutBucket(request); } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { Console.WriteLine("Please check the provided AWS Credentials."); Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3"); } else { Console.WriteLine("An Error, number {0}, occurred when creating a bucket with the message '{1}", amazonS3Exception.ErrorCode, amazonS3Exception.Message); } } } static void WritingAnObject() { try { // simple object put PutObjectRequest request = new PutObjectRequest() { ContentBody = "this is a test", BucketName = bucketName, Key = keyName }; PutObjectResponse response = client.PutObject(request); // put a more complex object with some metadata and http headers. PutObjectRequest titledRequest = new PutObjectRequest() { BucketName = bucketName, Key = keyName }; titledRequest.Metadata.Add("title", "the title"); client.PutObject(titledRequest); } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { Console.WriteLine("Please check the provided AWS Credentials."); Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3"); } else { Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message); } } } static void ReadingAnObject() { try { GetObjectRequest request = new GetObjectRequest() { BucketName = bucketName, Key = keyName }; using (GetObjectResponse response = client.GetObject(request)) { string title = response.Metadata["x-amz-meta-title"]; Console.WriteLine("The object's title is {0}", title); string dest = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), keyName); if (!File.Exists(dest)) { response.WriteResponseStreamToFile(dest); } } } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { Console.WriteLine("Please check the provided AWS Credentials."); Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3"); } else { Console.WriteLine("An error occurred with the message '{0}' when reading an object", amazonS3Exception.Message); } } } static void DeletingAnObject() { try { DeleteObjectRequest request = new DeleteObjectRequest() { BucketName = bucketName, Key = keyName }; client.DeleteObject(request); } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { Console.WriteLine("Please check the provided AWS Credentials."); Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3"); } else { Console.WriteLine("An error occurred with the message '{0}' when deleting an object", amazonS3Exception.Message); } } } static void ListingObjects() { try { ListObjectsRequest request = new ListObjectsRequest(); request.BucketName = bucketName; ListObjectsResponse response = client.ListObjects(request); foreach (S3Object entry in response.S3Objects) { Console.WriteLine("key = {0} size = {1}", entry.Key, entry.Size); } // list only things starting with "foo" request.Prefix = "foo"; response = client.ListObjects(request); foreach (S3Object entry in response.S3Objects) { Console.WriteLine("key = {0} size = {1}", entry.Key, entry.Size); } // list only things that come after "bar" alphabetically request.Prefix = null; request.Marker = "bar"; response = client.ListObjects(request); foreach (S3Object entry in response.S3Objects) { Console.WriteLine("key = {0} size = {1}", entry.Key, entry.Size); } // only list 3 things request.Prefix = null; request.Marker = null; request.MaxKeys = 3; response = client.ListObjects(request); foreach (S3Object entry in response.S3Objects) { Console.WriteLine("key = {0} size = {1}", entry.Key, entry.Size); } } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { Console.WriteLine("Please check the provided AWS Credentials."); Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3"); } else { Console.WriteLine("An error occurred with the message '{0}' when listing objects", amazonS3Exception.Message); } } } } }

Sample Details

Service: s3

Author: AWS

Type: full-example

On this page: