Sélectionner vos préférences de cookies

Nous utilisons des cookies essentiels et des outils similaires qui sont nécessaires au fonctionnement de notre site et à la fourniture de nos services. Nous utilisons des cookies de performance pour collecter des statistiques anonymes afin de comprendre comment les clients utilisent notre site et d’apporter des améliorations. Les cookies essentiels ne peuvent pas être désactivés, mais vous pouvez cliquer sur « Personnaliser » ou « Refuser » pour refuser les cookies de performance.

Si vous êtes d’accord, AWS et les tiers approuvés utiliseront également des cookies pour fournir des fonctionnalités utiles au site, mémoriser vos préférences et afficher du contenu pertinent, y compris des publicités pertinentes. Pour accepter ou refuser tous les cookies non essentiels, cliquez sur « Accepter » ou « Refuser ». Pour effectuer des choix plus détaillés, cliquez sur « Personnaliser ».

Amazon S3 Encryption Client for Go examples

Mode de mise au point
Amazon S3 Encryption Client for Go examples - Amazon S3 Encryption Client
Cette page n'a pas été traduite dans votre langue. Demande de traduction

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 3.x of the Amazon S3 Encryption Client for Go.

Note

The Amazon S3 Encryption Client for Go does not support asynchronous programming, multipart uploads, or ranged GET requests. To use these features with version 3.x of the Amazon S3 Encryption Client, you must use the Amazon S3 Encryption Client for Java.

Instantiating the Amazon S3 Encryption Client

After installing the Amazon S3 Encryption Client for Go, 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 when you instantiate the updated client. For more information, see Migrating to version 3.x of the Amazon S3 Encryption Client for Go.

The Amazon S3 Encryption Client for Go supports keyrings 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.

To use a KMS key as your wrapping key, you need kms:GenerateDataKey and kms:Decrypt permissions on the KMS key. To specify a KMS key, use any valid KMS key identifier. For details, see Key identifiers 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).

import ( ... // Import the materials and client package "github.com/aws/amazon-s3-encryption-client-go/client" "github.com/aws/amazon-s3-encryption-client-go/materials" ... ) 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

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 with a KMS key as your wrapping key when you instantiate your 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") }
  2. Encrypt your plaintext object by calling PutObject. 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.

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

    3. 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) }
  3. Decrypt your encrypted object by calling GetObject.

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

    2. 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") }
  4. 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) }

Rubrique suivante :

Migrate to version 3.x

Rubrique précédente :

Go
ConfidentialitéConditions d'utilisation du sitePréférences de cookies
© 2025, Amazon Web Services, Inc. ou ses affiliés. Tous droits réservés.