

# Amazon S3 Encryption Client for Go
<a name="go"></a>

**Note**  
This documentation describes the Amazon S3 Encryption Client version 3.*x* and newer, which is an independent library. For information about previous versions of the Amazon S3 Encryption Client, see the AWS SDK Developer Guide for your programming language. 

This topic explains how to install and use the Amazon S3 Encryption Client for Go. For details about programming with the Amazon S3 Encryption Client for Go, see the [amazon-s3-encryption-client-go](https://github.com/aws/amazon-s3-encryption-client-go) repository on GitHub.

**Topics**
+ [Prerequisites](#go-prerequisites)
+ [Installation](#go-installation)
+ [Amazon S3 Encryption Client for Go examples](go-examples.md)
+ [S3 Encryption Client Migration (3.*x* to 4.*x*)](go-v4-migration.md)
+ [S3 Encryption Client Migration (2.*x* to 3.*x*)](go-v3-migration.md)

## Prerequisites
<a name="go-prerequisites"></a>

Before you install the Amazon S3 Encryption Client for Go, be sure you have the following prerequisites.

**A Go development environment**  
The Amazon S3 Encryption Client for Go requires Go 1.24 or later, but we recommend that you use the latest version.  
You can view your current version of Go by running the following command.  

```
go version
```

**AWS SDK for Go 2.x**  
The Amazon S3 Encryption Client for Go requires the Amazon S3 and AWS KMS service clients of the AWS SDK for Go 2.x. For information on configuring AWS SDK for Go v2 service clients, see [Get started with the AWS SDK for Go v2](https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/getting-started.html) in the *AWS SDK for Go Developer Guide*.  
For information about updating your version of the AWS SDK for Go, see [Migrate to the AWS SDK for Go v2](https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/migrate-gosdk.html) in the *AWS SDK for Go Developer Guide*.

## Installation
<a name="go-installation"></a>

To install the Amazon S3 Encryption Client for Go and its dependencies, run the following Go command.

```
go get github.com/aws/amazon-s3-encryption-client-go
```

# Amazon S3 Encryption Client for Go examples
<a name="go-examples"></a>

The following examples show you how to use the Amazon S3 Encryption Client for Go to encrypt and decrypt Amazon S3 objects. These examples show how to use version 4.*x* of the Amazon S3 Encryption Client for Go. 

**Note**  
The Amazon S3 Encryption Client for Go does not support [asynchronous programming](using-s3ec-async.md), [multipart uploads](java-examples.md#multipart-upload), or [ranged GET requests](java-examples.md#ranged-gets). To use these features of the Amazon S3 Encryption Client, you must use the Amazon S3 Encryption Client for Java.

**Topics**
+ [Instantiating the Amazon S3 Encryption Client](#go-instantiate-client)
+ [Encrypting and decrypting Amazon S3 objects](#go-encrypt-example)

## Instantiating the Amazon S3 Encryption Client
<a name="go-instantiate-client"></a>

After [installing the Amazon S3 Encryption Client for Go](go.md#go-installation), you are ready to instantiate your client and begin encrypting and decrypting your Amazon S3 objects. If you have encrypted objects under a previous version of the Amazon S3 Encryption Client, you may need to enable legacy decryption modes or configure a commmitment policy when you instantiate the updated client. For more information, see [Migrating to version 4.*x* of the Amazon S3 Encryption Client for Go](go-v4-migration.md).

The Amazon S3 Encryption Client for Go supports [keyrings](concepts.md#keyring) that use symmetric encryption KMS keys as the wrapping key. The Amazon S3 Encryption Client for Go does not support keyrings that use Raw AES-GCM or Raw RSA wrapping keys. To use Raw AES-GCM or Raw RSA wrapping keys, you must use the Amazon S3 Encryption Client for Java. For more information, see [Instantiating the Amazon S3 Encryption Client for Java](java-examples.md#java-instantiate-client).

To use a KMS key as your wrapping key, you need [kms:GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html) and [kms:Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) permissions on the KMS key. To specify a KMS key, use any valid KMS key identifier. For details, see [Key identifiers](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id) in the *AWS Key Management Service Developer Guide*.

The following example instantiates the Amazon S3 Encryption Client with the default decryption mode. This means that all objects will be decrypted using the fully supported buffered decryption mode. For more information, see [Decryption modes (Version 3.*x* and later)](encryption-algorithms.md#decryption-modes).

```
import (
   ...
   // Import the materials and client package
   "github.com/aws/amazon-s3-encryption-client-go/client/v4"
   "github.com/aws/amazon-s3-encryption-client-go/materials/v4"
   ...
)
s3EncryptionClient, err := client.New(s3Client, cmm)

// Create the keyring and cryptographic materials manager (CMM)
cmm, err := materials.NewCryptographicMaterialsManager(materials.NewKmsKeyring(kmsClient, kmsKeyArn, func(options *materials.KeyringOptions) {
		options.EnableLegacyWrappingAlgorithms = false
}))
if err != nil {
	t.Fatalf("error while creating new CMM")
}

s3EncryptionClient, err := client.New(s3Client, cmm)
```

## Encrypting and decrypting Amazon S3 objects
<a name="go-encrypt-example"></a>

The following example shows you how to use the Amazon S3 Encryption Client for Go to encrypt and decrypt Amazon S3 objects.

1. Create a [keyring](concepts.md#keyring) with a KMS key as your wrapping key when you [instantiate your client](#go-instantiate-client). 

   ```
   s3Client = s3.NewFromConfig(cfg)
   kmsClient := kms.NewFromConfig(cfg)
   cmm, err := materials.NewCryptographicMaterialsManager(materials.NewKmsKeyring(kmsClient, kmsKeyArn, func(options *materials.KeyringOptions) {
       options.EnableLegacyWrappingAlgorithms = false
   }))
   if err != nil {
       t.Fatalf("error while creating new CMM")
   }
   ```

1. Encrypt your plaintext object by calling [https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html). To include an optional material description, add an `EncryptionContext` value to the `context` and supply this value to the `PutObject` request.

   1. The Amazon S3 Encryption Client provides the encryption materials: one plaintext data key and one copy of that data key encrypted by your wrapping key.

   1. The Amazon S3 Encryption Client uses the plaintext data key to encrypt your object, and then discards the plaintext data key.

   1. The Amazon S3 Encryption Client uploads the encrypted data key and the encrypted object to Amazon S3 as part of the `PutObject` call.

   ```
   ctx := context.Background()
   ...
   encryptionContext := context.WithValue(ctx, "EncryptionContext", map[string]string{"ec-key": "ec-value"})
   
   s3EncryptionClient, err := client.New(s3Client, cmm)
   _, err = s3EncryptionClient.PutObject(encryptionContext, &s3.PutObjectInput{
       Bucket: aws.String(bucket),
       Key:    aws.String(objectKey),
       Body:   bytes.NewReader([]byte(plaintext)),
   })
   
   if err != nil {
       t.Fatalf("error while encrypting: %v", err)
   }
   ```

1. Decrypt your encrypted object by calling [https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html).

   1. The Amazon S3 Encryption Client uses your wrapping key to decrypt the encrypted data key.

   1. The Amazon S3 Encryption Client uses the plaintext data key to decrypt the object, discards the plaintext data key, and returns the plaintext object as part of the `GetObject` call.

   ```
   result, err := s3EncryptionClient.GetObject(ctx, &s3.GetObjectInput{
   		Bucket: aws.String(bucket),
   		Key:    aws.String(objectKey),
   	})
   	if err != nil {
   		return fmt.Errorf("error while decrypting: %v", err)
   	}
   
   	decryptedPlaintext, err := io.ReadAll(result.Body)
   	if err != nil {
   		return fmt.Errorf("failed to read decrypted plaintext into byte array")
   	}
   ```

1. Optional: verify that the decrypted object matches the original plaintext object that you uploaded.

   ```
   if e, a := []byte(plaintext), decryptedPlaintext; !bytes.Equal(e, a) {
   		return fmt.Errorf("expect %v text, got %v", e, a)
   	}
   ```

# S3 Encryption Client Migration (3.*x* to 4.*x*)
<a name="go-v4-migration"></a>

**Note:** If you're using version 2.*x* of the Amazon S3 Encryption Client for Go and want to migrate to version 4.*x*, you must first migrate to version 3.*x*. See [S3 Encryption Client Migration (2.*x* to 3.*x*)](go-v3-migration.md).

Version 4.*x* of the Amazon S3 Encryption Client for Go introduces AES GCM with Key Commitment (ALG\$1AES\$1256\$1GCM\$1HKDF\$1SHA512\$1COMMIT\$1KEY) and Commitment Policies to enhance security by protecting against data key tampering in Instruction Files. This migration guide explains the two-phase approach to safely upgrade from 3.*x* to 4.*x* while maintaining backward compatibility during the transition.

## Migration Overview
<a name="go-v4-migration-overview"></a>

Migrating from version 3.*x* to version 4.*x* of the Amazon S3 Encryption Client for Go requires a two-phase approach to ensure compatibility and security:

1. **Phase 1: Update existing 3.*x* clients to read 4.*x* formats**

   First, update all existing 3.*x* clients in your environment to a version that can read objects encrypted with 4.*x* algorithms and commitment policies (Amazon S3 Encryption Client for Go version 3.2.0 or greater). This ensures that when you start encrypting with 4.*x*, your existing applications can still decrypt the new objects.

1. **Phase 2: Migrate encryption and decryption clients to 4.*x***

   After all clients can read 4.*x* formats, migrate your encryption and decryption operations to use 4.*x* clients with the appropriate Commitment Policy. This phase introduces the enhanced security features while maintaining backward compatibility with existing encrypted objects.

This phased approach prevents compatibility issues and ensures that all encrypted objects remain accessible throughout the migration process.

## Understanding 4.*x* Concepts
<a name="go-v4-migration-concepts"></a>

Version 4.*x* introduces two key security concepts that enhance protection against data key tampering:

### Commitment Policy
<a name="go-v4-migration-commitment-policy"></a>

Commitment Policy controls how the encryption client handles key commitment during encryption and decryption operations. There are three Commitment Policies:

`FORBID_ENCRYPT_ALLOW_DECRYPT`  
**Encryption:** Encrypts without commitment.  
**Decryption:** Allows decryption of both committing and non-committing objects.  
**Security:** Does not enforce commitment and may allow for tampering of data keys in Instruction Files. Use only during migration for backward compatibility.  
**Version Compatibility:** Objects encrypted with this policy can be read by 2.*x*, 3.*x*, and 4.*x* clients.

`REQUIRE_ENCRYPT_ALLOW_DECRYPT`  
**Encryption:** Encrypts with commitment (uses ALG\$1AES\$1256\$1GCM\$1HKDF\$1SHA512\$1COMMIT\$1KEY algorithm).  
**Decryption:** Allows decryption of both committing and non-committing objects.  
**Security:** New objects are protected against tampering in Instruction Files. Old objects remain readable, but are not protected against data key tampering.  
**Version Compatibility:** Objects encrypted with this policy can only be read by 3.*x* clients (Amazon S3 Encryption Client for Go version 3.2.0 or greater) and 4.*x* clients.

`REQUIRE_ENCRYPT_REQUIRE_DECRYPT` (Default for 4.*x*)  
**Encryption:** Encrypts with commitment (uses ALG\$1AES\$1256\$1GCM\$1HKDF\$1SHA512\$1COMMIT\$1KEY algorithm).  
**Decryption:** Only allows decryption of objects encrypted with key commitment.  
**Security:** Strict commitment enforcement provides protection against tampered data keys.  
**Version Compatibility:** Objects encrypted with this policy can only be read by 3.*x* clients (version 3.2.0 or greater) and 4.*x* clients. This policy will reject non-committing objects during decryption.

### AES GCM with Key Commitment
<a name="go-v4-migration-aes-gcm-kc"></a>

AES GCM with Key Commitment (ALG\$1AES\$1256\$1GCM\$1HKDF\$1SHA512\$1COMMIT\$1KEY) is the new encryption algorithm suite introduced in version 4.*x* that protects against data key tampering in Instruction Files by cryptographically binding the key to its intended use.

**Version Compatibility:** Objects encrypted with ALG\$1AES\$1256\$1GCM\$1HKDF\$1SHA512\$1COMMIT\$1KEY can only be decrypted by 3.*x* clients (version 3.2.0 or greater) or 4.*x* clients. 2.*x* and earlier 3.*x* clients (v3.1.0 and earlier) cannot read these objects.

## Update Existing Clients
<a name="go-v4-migration-update-clients"></a>

Before migrating to 4.*x* encryption, you must first update all existing 3.*x* clients to a version that can read 4.*x* encrypted objects. This ensures compatibility when you begin encrypting with 4.*x*.

### Build and Install the Latest SDK Version
<a name="go-v4-migration-build-install"></a>

Update your Go module dependencies to use the latest version of the Amazon S3 Encryption Client for Go 3.*x* that includes support for reading 4.*x* messages:

**Update Go modules:**

```
go get github.com/aws/amazon-s3-encryption-client-go/v3@latest
```

**Update your go.mod file if needed:**

```
module your-application

go 1.24

require (
    // The `x`s must be replaced with the specific latest version
    github.com/aws/amazon-s3-encryption-client-go/v3 v3.x.x
    // Add other dependencies as needed
)
```

### Build, Install, and Deploy Applications
<a name="go-v4-migration-build-deploy"></a>

After updating your dependencies, rebuild and deploy your applications:

1. **Clean and rebuild:**

   ```
   go mod tidy
   go build ./...
   ```

1. **Run your tests:**

   ```
   go test ./...
   ```

1. **Deploy updated applications:** Deploy the updated applications to all environments where S3 Encryption Client is used. Ensure all applications can successfully decrypt existing V3 encrypted objects before proceeding to the next phase.

## Migrate to V4
<a name="go-v4-migration-migrate"></a>

After all clients in your environment can read 4.*x* formats, you can migrate your encryption and decryption operations to use 4.*x* clients. The following examples demonstrate the transition from 3.*x* to 4.*x* clients.

### Client Migration Examples
<a name="go-v4-migration-client-transition"></a>

The following examples show how to migrate from 3.*x* to 4.*x* clients using different Commitment Policies during the transition:

**Pre-migration (3.*x* Client)**

```
import (
	"context"
	"fmt"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/kms"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	
	// V3 S3 Encryption Client imports
	"github.com/aws/amazon-s3-encryption-client-go/v3/client"
	"github.com/aws/amazon-s3-encryption-client-go/v3/materials"
)

func V3EncryptionExample() error {
	ctx := context.Background()
	
	// Load AWS configuration
	cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-west-2"))
	if err != nil {
		return fmt.Errorf("failed to load config: %v", err)
	}

	// Create KMS and S3 clients
	kmsClient := kms.NewFromConfig(cfg)
	s3Client := s3.NewFromConfig(cfg)
	
	// Create V3 encryption materials
	kmsKeyId := "arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012"
	cmm, err := materials.NewCryptographicMaterialsManager(
		materials.NewKmsKeyring(kmsClient, kmsKeyId))
	if err != nil {
		return fmt.Errorf("failed to create CMM: %v", err)
	}

	// Create V3 S3 encryption client
	s3EncryptionClient, err := client.New(s3Client, cmm)
	if err != nil {
		return fmt.Errorf("failed to create encryption client: %v", err)
	}

	// Encrypt and upload object
	encryptionContext := map[string]string{
		"purpose": "example",
		"department": "engineering",
	}
	
	_, err = s3EncryptionClient.PutObject(ctx, &s3.PutObjectInput{
		Bucket: aws.String("my-bucket"),
		Key:    aws.String("my-object"),
		Body:   strings.NewReader("Hello, World!"),
		Metadata: encryptionContext,
	})
	
	return err
}
```

**During Migration (4.*x* Client with FORBID\$1ENCRYPT\$1ALLOW\$1DECRYPT Policy)**

Update your Go module dependencies to use the latest version of the Amazon S3 Encryption Client for Go 4.*x*:

**Upgrade Go modules:**

```
go get github.com/aws/amazon-s3-encryption-client-go/v4@latest
```

**Update your go.mod file if needed:**

```
module your-application

go 1.24

require (
    // The `x`s must be replaced with the specific latest version
    github.com/aws/amazon-s3-encryption-client-go/v4 v4.x.x
    // Add other dependencies as needed
)
```

After updating your dependencies, make code changes as described below. This should result in no functional changes to your application.

```
import (
	"context"
	"fmt"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/kms"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	
	// V4 S3 Encryption Client imports
	"github.com/aws/amazon-s3-encryption-client-go/v4/client"
	"github.com/aws/amazon-s3-encryption-client-go/v4/commitment"
	"github.com/aws/amazon-s3-encryption-client-go/v4/materials"
)

func V4ForbidAllowExample() error {
	ctx := context.Background()
	
	// Load AWS configuration
	cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-west-2"))
	if err != nil {
		return fmt.Errorf("failed to load config: %v", err)
	}

	// Create KMS and S3 clients
	kmsClient := kms.NewFromConfig(cfg)
	s3Client := s3.NewFromConfig(cfg)
	
	// Create V4 encryption materials with KMS keyring
	kmsKeyId := "arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012"
	cmm, err := materials.NewCryptographicMaterialsManager(
		materials.NewKmsKeyring(kmsClient, kmsKeyId))
	if err != nil {
		return fmt.Errorf("failed to create CMM: %v", err)
	}

	// Create V4 S3 encryption client with FORBID_ENCRYPT_ALLOW_DECRYPT policy
	// This maintains V3 compatibility during migration
	s3EncryptionClient, err := client.New(s3Client, cmm, func(options *client.EncryptionClientOptions) {
		// This MUST be explicitly configured to FORBID_ENCRYPT_ALLOW_DECRYPT.
		// While FORBID_ENCRYPT_ALLOW_DECRYPT is the default for v3 clients,
		// v4 clients default to REQUIRE_ENCRYPT_REQUIRE_DECRYPT.
		// This configuration ensures identical behavior to a v3 client.
		options.CommitmentPolicy = commitment.FORBID_ENCRYPT_ALLOW_DECRYPT
	})
	if err != nil {
		return fmt.Errorf("failed to create V4 encryption client: %v", err)
	}

	// Encrypt and upload object (uses legacy algorithms for V3 compatibility)
	encryptionContext := map[string]string{
		"purpose": "example",
		"department": "engineering",
	}
	
	_, err = s3EncryptionClient.PutObject(ctx, &s3.PutObjectInput{
		Bucket: aws.String("my-bucket"),
		Key:    aws.String("my-object"),
		Body:   strings.NewReader("Hello, World!"),
		Metadata: encryptionContext,
	})
	
	return err
}
```

**During migration (4.*x* Client with REQUIRE\$1ENCRYPT\$1ALLOW\$1DECRYPT Policy)**

After deploying the FORBID\$1ENCRYPT\$1ALLOW\$1DECRYPT changes, make code changes as described below. This will cause your application to start writing objects encrypted with key committing algorithms.

```
import (
	"context"
	"fmt"
	"io"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/kms"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	
	// V4 S3 Encryption Client imports
	"github.com/aws/amazon-s3-encryption-client-go/v4/client"
    "github.com/aws/amazon-s3-encryption-client-go/v4/commitment"
	"github.com/aws/amazon-s3-encryption-client-go/v4/materials"
)

func V4RequireAllowExample() error {
	ctx := context.Background()
	
	// Load AWS configuration
	cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-west-2"))
	if err != nil {
		return fmt.Errorf("failed to load config: %v", err)
	}

	// Create KMS and S3 clients
	kmsClient := kms.NewFromConfig(cfg)
	s3Client := s3.NewFromConfig(cfg)
	
	// Create V4 encryption materials with KMS keyring
	kmsKeyId := "arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012"
	cmm, err := materials.NewCryptographicMaterialsManager(
		materials.NewKmsKeyring(kmsClient, kmsKeyId))
	if err != nil {
		return fmt.Errorf("failed to create CMM: %v", err)
	}

	// Create V4 S3 encryption client with REQUIRE_ENCRYPT_ALLOW_DECRYPT commitment policy
	// Uses REQUIRE_ENCRYPT_ALLOW_DECRYPT to ensure new messages are encrypted with key commitment
	s3EncryptionClient, err := client.New(s3Client, cmm, func(options *client.EncryptionClientOptions) {
		// Migration note: The commitment policy has been updated to REQUIRE_ENCRYPT_ALLOW_DECRYPT.
		// This change causes the client to start writing objects encrypted with key committing algorithms.
		// The client will continue to be able to read objects encrypted with either
		// key committing or non-key committing algorithms.
		options.CommitmentPolicy = commitment.REQUIRE_ENCRYPT_ALLOW_DECRYPT
	})
	if err != nil {
		return fmt.Errorf("failed to create V4 encryption client: %v", err)
	}

	// Encrypt and upload object (uses AES_GCM_KC with key commitment)
	encryptionContext := map[string]string{
		"purpose": "example",
		"department": "engineering",
	}
	
	_, err = s3EncryptionClient.PutObject(ctx, &s3.PutObjectInput{
		Bucket: aws.String("my-bucket"),
		Key:    aws.String("my-object"),
		Body:   strings.NewReader("Hello, World!"),
		Metadata: encryptionContext,
	})
	if err != nil {
		return fmt.Errorf("failed to put object: %v", err)
	}

	// Decrypt and download object
	result, err := s3EncryptionClient.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String("my-bucket"),
		Key:    aws.String("my-object"),
	})
	if err != nil {
		return fmt.Errorf("failed to get object: %v", err)
	}
	defer result.Body.Close()

	// Read decrypted content
	body, err := io.ReadAll(result.Body)
	if err != nil {
		return fmt.Errorf("failed to read body: %v", err)
	}
	
	fmt.Printf("Decrypted content: %s\n", string(body))
	return nil
}
```

**Post-migration (4.*x* Client with default commitment policy)**

After deploying the REQUIRE\$1ENCRYPT\$1ALLOW\$1DECRYPT changes, make code changes as described below. This will cause your application to stop reading objects encrypted without key committing algorithms. Before deploying this change, ensure all existing objects are now encrypted with key commiting algorithms.

```
import (
	"context"
	"fmt"
	"io"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/kms"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	
	// V4 S3 Encryption Client imports
	"github.com/aws/amazon-s3-encryption-client-go/v4/client"
	"github.com/aws/amazon-s3-encryption-client-go/v4/materials"
)

func V4KeyCommitmentExample() error {
	ctx := context.Background()
	
	// Load AWS configuration
	cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-west-2"))
	if err != nil {
		return fmt.Errorf("failed to load config: %v", err)
	}

	// Create KMS and S3 clients
	kmsClient := kms.NewFromConfig(cfg)
	s3Client := s3.NewFromConfig(cfg)
	
	// Create V4 encryption materials with KMS keyring
	kmsKeyId := "arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012"
	cmm, err := materials.NewCryptographicMaterialsManager(
		materials.NewKmsKeyring(kmsClient, kmsKeyId))
	if err != nil {
		return fmt.Errorf("failed to create CMM: %v", err)
	}

	// Create V4 S3 encryption client with default commitment policy (REQUIRE_ENCRYPT_REQUIRE_DECRYPT)
	// Uses REQUIRE_ENCRYPT_ALLOW_DECRYPT to ensure all messages read or written are encrypted with key commitment
	s3EncryptionClient, err := client.New(s3Client, cmm)
	if err != nil {
		return fmt.Errorf("failed to create V4 encryption client: %v", err)
	}

	// Encrypt and upload object (uses AES_GCM_KC with key commitment)
	encryptionContext := map[string]string{
		"purpose": "example",
		"department": "engineering",
	}
	
	_, err = s3EncryptionClient.PutObject(ctx, &s3.PutObjectInput{
		Bucket: aws.String("my-bucket"),
		Key:    aws.String("my-object"),
		Body:   strings.NewReader("Hello, World!"),
		Metadata: encryptionContext,
	})
	if err != nil {
		return fmt.Errorf("failed to put object: %v", err)
	}

	// Decrypt and download object
	result, err := s3EncryptionClient.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String("my-bucket"),
		Key:    aws.String("my-object"),
	})
	if err != nil {
		return fmt.Errorf("failed to get object: %v", err)
	}
	defer result.Body.Close()

	// Read decrypted content
	body, err := io.ReadAll(result.Body)
	if err != nil {
		return fmt.Errorf("failed to read body: %v", err)
	}
	
	fmt.Printf("Decrypted content: %s\n", string(body))
	return nil
}
```

## Additional Examples
<a name="go-v4-migration-examples"></a>

The following examples demonstrate specific 4.*x* configuration scenarios for different migration and operational needs.

### Enable Legacy Support for Reading 1.*x*/2.*x* Objects
<a name="go-v4-migration-legacy-support"></a>

During migration, you may need to read objects encrypted with legacy algorithms. Configure your 4.*x* client to support backward compatibility:

```
import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/kms"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	
	// V4 S3 Encryption Client imports
	"github.com/aws/amazon-s3-encryption-client-go/v4/client"
	"github.com/aws/amazon-s3-encryption-client-go/v4/commitment"
	"github.com/aws/amazon-s3-encryption-client-go/v4/materials"
)

func V4WithLegacySupportExample() error {
	ctx := context.Background()
	
	// Load AWS configuration
	cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-west-2"))
	if err != nil {
		return fmt.Errorf("failed to load config: %v", err)
	}

	// Create KMS and S3 clients
	kmsClient := kms.NewFromConfig(cfg)
	s3Client := s3.NewFromConfig(cfg)
	
	// Create encryption materials
	kmsKeyId := "arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012"
	cmm, err := materials.NewCryptographicMaterialsManager(
		materials.NewKmsKeyring(kmsClient, kmsKeyId, func(options *materials.KeyringOptions) {
			// Enable legacy wrapping algorithms for V2/V3 compatibility
			options.EnableLegacyWrappingAlgorithms = true
		}))
	if err != nil {
		return fmt.Errorf("failed to create CMM: %v", err)
	}

	// Create V4 client with legacy support enabled
	s3EncryptionClient, err := client.New(s3Client, cmm, func(options *client.EncryptionClientOptions) {
		// Allow reading objects encrypted with legacy algorithms
		options.EnableLegacyUnauthenticatedModes = true
		// Use REQUIRE_ENCRYPT_ALLOW_DECRYPT to encrypt with commitment but read legacy objects
		options.CommitmentPolicy = commitment.REQUIRE_ENCRYPT_ALLOW_DECRYPT
	})
	if err != nil {
		return fmt.Errorf("failed to create encryption client: %v", err)
	}

	// This client can now read objects encrypted with legacy algorithms and encrypt new objects with commitment
	result, err := s3EncryptionClient.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String("my-bucket"),
		Key:    aws.String("legacy-encrypted-object"),
	})
	if err != nil {
		return fmt.Errorf("failed to decrypt legacy object: %v", err)
	}
	defer result.Body.Close()

	return nil
}
```

# S3 Encryption Client Migration (2.*x* to 3.*x*)
<a name="go-v3-migration"></a>

**Note:** If you're using version 3.*x* of the Amazon S3 Encryption Client for Go and want to migrate to version 4.*x*, see [S3 Encryption Client Migration (3.*x* to 4.*x*)](go-v4-migration.md).

With version 3.*x* of the Amazon S3 Encryption Client for Go, you create one client for both encryption and decryption. Version 3.*x* replaces the cipher data generators with the cryptographic materials manager (CMM), and replaces the KMS key providers, `NewKMSContextKeyGenerator`, with the `NewKmsKeyring`.

When updating from earlier versions of the Amazon S3 Encryption Client to version 3.*x*, you need to update your client builder code to use the new, simpler client. If you're decrypting ciphertext that was encrypted by earlier versions of the Amazon S3 Encryption Client, you might also need to allow the Amazon S3 Encryption Client to [decrypt legacy encryption algorithms](#enable-legacy-go-v3).

The following examples show the equivalent code required to specify a KMS key provider with a KMS key ID in versions 1.*x*, 2.*x*, and 3.*x* of the Amazon S3 Encryption Client.

------
#### [ Version 1.*x* ]

In version 1.*x*, you use the `NewKMSKeyGeneratorWith` function to construct the `cipherDataGenerator`.

```
sess := session.Must(session.NewSession())
kmsClient := kms.New(sess)
cmkID := "1234abcd-12ab-34cd-56ef-1234567890ab"

cipherDataGenerator := s3crypto.NewKMSKeyGenerator(kmsClient, kmsKeyID)
```

------
#### [ Version 2.*x* ]

In version 2.*x*, you use the `NewKMSContextKeyGenerator` function to construct the `cipherDataGenerator`.

```
sess := session.Must(session.NewSession())
kmsClient := kms.New(sess)
cmkID := "1234abcd-12ab-34cd-56ef-1234567890ab"
var matDesc s3crypto.MaterialDescription

// changed NewKMSKeyGenerator to NewKMSContextKeyGenerator
cipherDataGenerator := s3crypto.NewKMSContextKeyGenerator(kmsClient, kmsKeyID, matDesc)
```

------
#### [ Version 3.*x* ]

In version 3.*x*, you use the `NewKmsKeyring` function to construct your cryptographic materials manager (CMM).

```
s3Client := s3.NewFromConfig(cfg)
kmsClient := kms.NewFromConfig(cfg)
cmm, err := materials.NewCryptographicMaterialsManager(materials.NewKmsKeyring(kmsClient, kmsKeyID))
	if err != nil {
		return fmt.Errorf("error while creating new CMM")
	}
```

------

## Migrating from version 2.*x*
<a name="migrate-v2-to-v3"></a>

The following example demonstrates how to migrate a version 2.*x* application that uses the `NewKMSContextKeyGenerator` KMS key provider with a material description and `AESGCMContentCipherBuilderV2` content cipher to version 3.*x* of the Amazon S3 Encryption Client for Go.

```
import (
	"bytes"
	"context"
	"fmt"
	"log"

	// AWS SDK for Go v1 (for V2 S3EC)
	awsV1 "github.com/aws/aws-sdk-go/aws"
	sessionV1 "github.com/aws/aws-sdk-go/aws/session"
	kmsV1 "github.com/aws/aws-sdk-go/service/kms"
	s3V1 "github.com/aws/aws-sdk-go/service/s3"
	s3cryptoV2 "github.com/aws/aws-sdk-go/service/s3/s3crypto"

	// AWS SDK for Go v2 (for V3 S3EC)
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/kms"
	"github.com/aws/aws-sdk-go-v2/service/s3"

	// V3 S3 Encryption Client imports
	"github.com/aws/amazon-s3-encryption-client-go/v3/client"
	"github.com/aws/amazon-s3-encryption-client-go/v3/materials"
)

func KmsContextV2toV3GCMExample() error {
	bucket := LoadBucket()
	kmsKeyAlias := LoadAwsKmsAlias()

	objectKey := "my-object-key"
	region := "us-west-2"
	plaintext := "This is an example.\n"

	// Create an S3EC Go v2 encryption client
	// using the KMS client from AWS SDK for Go v1
	sessKms, err := sessionV1.NewSession(&awsV1.Config{
		Region: aws.String(region),
	})

	kmsSvc := kmsV1.New(sessKms)
	handler := s3cryptoV2.NewKMSContextKeyGenerator(kmsSvc, kmsKeyAlias, s3cryptoV2.MaterialDescription{})
	builder := s3cryptoV2.AESGCMContentCipherBuilderV2(handler)
	encClient, err := s3cryptoV2.NewEncryptionClientV2(sessKms, builder)
	if err != nil {
		log.Fatalf("error creating new v2 client: %v", err)
	}

	// Encrypt using KMS+Context and AES-GCM content cipher
	_, err = encClient.PutObject(&s3V1.PutObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(objectKey),
		Body:   bytes.NewReader([]byte(plaintext)),
	})
	if err != nil {
		log.Fatalf("error calling putObject: %v", err)
	}
	fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key)

	// Create an S3EC Go v3 client
	// using the KMS client from AWS SDK for Go v2
	ctx := context.Background()
	cfg, err := config.LoadDefaultConfig(ctx,
		config.WithRegion(region),
	)

	kmsV2 := kms.NewFromConfig(cfg)
	cmm, err := materials.NewCryptographicMaterialsManager(materials.NewKmsKeyring(kmsV2, kmsKeyAlias))
	if err != nil {
		t.Fatalf("error while creating new CMM")
	}

	s3V2 := s3.NewFromConfig(cfg)
	s3ecV3, err := client.New(s3V2, cmm)

	result, err := s3ecV3.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(objectKey),
	})
	if err != nil {
		t.Fatalf("error while decrypting: %v", err)
	}
}
```

## Enable legacy decryption modes
<a name="enable-legacy-go-v3"></a>

If you need to decrypt objects or data keys that were encrypted with a legacy algorithm, or you need to partially decrypt an AES-GCM encrypted object when performing a [ranged request](java-examples.md#ranged-gets), you need to explicitly enable this behavior when you instantiate the client.

Version 3.*x* of the Amazon S3 Encryption Client encrypts only with [fully supported algorithms](encryption-algorithms.md#v3-algorithms). It will never encrypt with a legacy algorithm. By default, it decrypts only with fully supported algorithms, but you can enable it to decrypt with both fully supported and legacy algorithms. For more information, see [Decryption modes (Amazon S3 Encryption Client for Java version 3.*x* and later)](encryption-algorithms.md#decryption-modes).

The `enableLegacyUnauthenticatedModes` flag enables the Amazon S3 Encryption Client to decrypt encrypted objects with a fully supported or legacy encryption algorithm.

Version 3.*x* of the Amazon S3 Encryption Client uses one of the fully supported wrapping algorithms and the wrapping key you specify to encrypt and decrypt the data keys. The `enableLegacyWrappingAlgorithms` flag enables the Amazon S3 Encryption Client to decrypt encrypted data keys with a fully supported or legacy wrapping algorithm.

If your client doesn't include the necessary legacy decryption mode with a value of `true`, and it encounters an object encrypted with a legacy algorithm, it throws `S3EncryptionClientException`.

The following example enables the `enableLegacyUnauthenticatedModes` and `enableLegacyWrappingAlgorithms` flags. This client always encrypts only with fully supported algorithms. However, it can decrypt objects and data keys encrypted with fully supported or legacy algorithms.

```
cmm, err := materials.NewCryptographicMaterialsManager(materials.NewKmsKeyring(kmsClient, , func(options *materials.KeyringOptions) {
    options.EnableLegacyWrappingAlgorithms = true
})

if err != nil {
	t.Fatalf("error while creating new CMM")
}

client, err := client.New(s3Client, cmm, func(clientOptions *client.EncryptionClientOptions) {
		clientOptions.EnableLegacyUnauthenticatedModes = true
})

if err != nil {
	// handle error
}
```

The legacy decryption modes are designed to be a temporary fix. After you've re-encrypted all of your objects with fully supported algorithms, you can eliminate it from your code.