AWS Developer Blog

Using AWS KMS Master Keys with the AmazonS3EncryptionClient in the AWS SDK for .NET

You can now use an AWS KMS key as your master key when you use the AmazonS3EncryptionClient class for client-side encryption.

The main advantage of using an AWS KMS key as your master key is that you don’t need to store and manage your own master keys. It’s done by AWS. A second advantage of the new feature is that it makes the AWS SDK for .NET’s AmazonS3EncryptionClient class interoperable with the AWS SDK for Java’s AmazonS3EncryptionClient class.* This means you can encrypt with the AWS SDK for Java and decrypt with the AWS SDK for .NET, and vice versa.

For more information about client-side encryption with the AmazonS3EncryptionClient class, and how envelope encryption works, see our original blog post.

The following examples demonstrate how to use AWS KMS keys with the AmazonS3EncryptionClient class. Note that your project must reference the latest version of the AWSSDK.KeyManagementService Nuget package to use this feature.

// Encryption
// ----------
var bucketName = "bucket";
var kmsKeyID = "kms-key-id";
var objectKey = "key";
var objectContent = "object content";

var kmsEncryptionMaterials = new EncryptionMaterials(kmsKeyID);
// CryptoStorageMode.ObjectMetadata is required for KMS EncryptionMaterials
var config = new AmazonS3CryptoConfiguration()
{
    StorageMode = CryptoStorageMode.ObjectMetadata
};

using (var client = new AmazonS3EncryptionClient(config, kmsEncryptionMaterials))
{
    var request = new PutObjectRequest
    {
        BucketName = bucketName,
        Key = objectKey,
        ContentBody = objectContent
    };
    client.PutObject(request);
}

// Decryption
// ----------
var bucketName = "bucket";
var kmsKeyID = "kms-key-id";
var objectKey = "key";
string objectContent = null;

var kmsEncryptionMaterials = new EncryptionMaterials(kmsKeyID);
// CryptoStorageMode.ObjectMetadata is required for KMS EncryptionMaterials
var config = new AmazonS3CryptoConfiguration()
{
    StorageMode = CryptoStorageMode.ObjectMetadata
};

using (var client = new AmazonS3EncryptionClient(config, kmsEncryptionMaterials))
{
    var request = new GetObjectRequest
    {
        BucketName = bucketName,
        Key = objectKey
    };

    using (var response = client.GetObject(request))
    using (var stream = response.ResponseStream)
    using (var reader = new StreamReader(stream))
    {
        objectContent = reader.ReadToEnd();
    }
}
// use objectContent

*The AWS SDK for .NET’s AmazonS3EncryptionClient only supports KMS master keys when run in metadata mode. The instruction file mode of the AWS SDK for .NET’s AmazonS3EncryptionClient is still incompatible with the AWS SDK for Java’s AmazonS3EncryptionClient.


+ Recent posts