View a markdown version of this page

AWS Encryption SDK 对于 Go 示例代码 - AWS Encryption SDK

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

AWS Encryption SDK 对于 Go 示例代码

以下示例显示了使用 AWS Encryption SDK for Go 进行编程时使用的基本编码模式。具体而言,您可以对 AWS Encryption SDK 和材质提供者库进行实例化。然后,在调用每个方法之前,您需要实例化定义该方法输入的对象。

有关说明如何在中配置选项的示例 AWS Encryption SDK,例如指定备用算法套件和限制加密数据密钥,请参阅 aws-encryption-sdk 存储库中的 Go 示例。 GitHub

加密和解密中的数据 AWS Encryption SDK for Go

此示例显示了加密和解密数据的基本模式。它使用受一个 AWS KMS 包装密钥保护的数据密钥对少量数据进行加密。

步骤 1:实例化. AWS Encryption SDK

您将使用中的 AWS Encryption SDK 方法加密和解密数据。

import ( "context" mpl "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygenerated" mpltypes "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygeneratedtypes" client "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygenerated" esdktypes "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygeneratedtypes" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/kms" ) encryptionClient, err := client.NewClient(esdktypes.AwsEncryptionSdkConfig{}) if err != nil { panic(err) }
第 2 步:创建 AWS KMS 客户端。
cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic(err) } kmsClient := kms.NewFromConfig(cfg, func(o *kms.Options) { o.Region = KmsKeyRegion })
可选:创建您的加密上下文。
encryptionContext := map[string]string{ "encryption": "context", "is not": "secret", "but adds": "useful metadata", "that can help you": "be confident that", "the data you are handling": "is what you think it is", }
第 3 步:实例化材料提供者库。

您将使用材料提供程序库中的方法创建密钥环,密钥环指定哪些密钥保护您的数据。

matProv, err := mpl.NewClient(mpltypes.MaterialProvidersConfig{}) if err != nil { panic(err) }
第 4 步:创建 AWS KMS 密钥环。

要创建密钥环,请使用密钥环输入对象调用密钥环方法。此示例使用该CreateAwsKmsKeyring方法并指定了一个 KMS 密钥。该kmsKeyId变量代表您提供的 KMS 密钥的密钥 ARN。

awsKmsKeyringInput := mpltypes.CreateAwsKmsKeyringInput{ KmsClient: kmsClient, KmsKeyId: kmsKeyId, } awsKmsKeyring, err := matProv.CreateAwsKmsKeyring(context.Background(), awsKmsKeyringInput) if err != nil { panic(err) }
第 5 步:加密明文。
res, err := encryptionClient.Encrypt(context.Background(), esdktypes.EncryptInput{ Plaintext: []byte(exampleText), EncryptionContext: encryptionContext, Keyring: awsKmsKeyring, }) if err != nil { panic(err) } ciphertext := res.Ciphertext
第 6 步:使用您在加密时使用的相同密钥环解密您的加密数据。
decryptOutput, err := encryptionClient.Decrypt(context.Background(), esdktypes.DecryptInput{ Ciphertext: ciphertext, // Provide the encryption context that was supplied to the encrypt method EncryptionContext: encryptionContext, Keyring: awsKmsKeyring, }) if err != nil { panic(err) } decrypted := decryptOutput.Plaintext