Skip to content

refactor(Go): Update examples to use utils and fix var name #1860

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
May 7, 2025
29 changes: 9 additions & 20 deletions Examples/runtimes/go/keyring/awskmskeyring.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
dbesdkdynamodbencryptiontypes "github.com/aws/aws-database-encryption-sdk-dynamodb/awscryptographydbencryptionsdkdynamodbsmithygeneratedtypes"
dbesdkstructuredencryptiontypes "github.com/aws/aws-database-encryption-sdk-dynamodb/awscryptographydbencryptionsdkstructuredencryptionsmithygeneratedtypes"
"github.com/aws/aws-database-encryption-sdk-dynamodb/dbesdkmiddleware"
"github.com/aws/aws-database-encryption-sdk-dynamodb/examples/utils"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
Expand Down Expand Up @@ -40,27 +41,21 @@ func AwsKmsKeyringExample(kmsKeyID, ddbTableName string) {
// We will use the `CreateMrkMultiKeyring` method to create this keyring,
// as it will correctly handle both single region and Multi-Region KMS Keys.
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
panic(err)
}
utils.HandleError(err)
// Create KMS client
kmsClient := kms.NewFromConfig(cfg, func(o *kms.Options) {
o.Region = "us-west-2"
})
// Initialize the mpl client
matProv, err := mpl.NewClient(mpltypes.MaterialProvidersConfig{})
if err != nil {
panic(err)
}
utils.HandleError(err)
// Create the Aws Kms Keyring
awsKmsKeyringInput := mpltypes.CreateAwsKmsKeyringInput{
KmsClient: kmsClient,
KmsKeyId: kmsKeyID,
}
keyring, err := matProv.CreateAwsKmsKeyring(context.Background(), awsKmsKeyringInput)
if err != nil {
panic(err)
}
utils.HandleError(err)

// 2. Configure which attributes are encrypted and/or signed when writing new items.
// For each attribute that may exist on the items we plan to write to our DynamoDbTable,
Expand Down Expand Up @@ -109,15 +104,15 @@ func AwsKmsKeyringExample(kmsKeyID, ddbTableName string) {
// 4. Create the DynamoDb Encryption configuration for the table we will be writing to.
partitionKey := "partition_key"
sortKeyName := "sort_key"
algorithmSuiteId := mpltypes.DBEAlgorithmSuiteIdAlgAes256GcmHkdfSha512CommitKeyEcdsaP384SymsigHmacSha384
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixing this to make Go idiomatic as in https://go.dev/wiki/CodeReviewComments#initialisms

algorithmSuiteID := mpltypes.DBEAlgorithmSuiteIdAlgAes256GcmHkdfSha512CommitKeyEcdsaP384SymsigHmacSha384
tableConfig := dbesdkdynamodbencryptiontypes.DynamoDbTableEncryptionConfig{
LogicalTableName: ddbTableName,
PartitionKeyName: partitionKey,
SortKeyName: &sortKeyName,
AttributeActionsOnEncrypt: attributeActions,
Keyring: keyring,
AllowedUnsignedAttributePrefix: &allowedUnsignedAttributePrefix,
AlgorithmSuiteId: &algorithmSuiteId,
AlgorithmSuiteId: &algorithmSuiteID,
}
tableConfigsMap := make(map[string]dbesdkdynamodbencryptiontypes.DynamoDbTableEncryptionConfig)
tableConfigsMap[ddbTableName] = tableConfig
Expand All @@ -126,9 +121,7 @@ func AwsKmsKeyringExample(kmsKeyID, ddbTableName string) {
}
// 5. Create a new AWS SDK DynamoDb client using the TableEncryptionConfigs
dbEsdkMiddleware, err := dbesdkmiddleware.NewDBEsdkMiddleware(listOfTableConfigs)
if err != nil {
panic(err)
}
utils.HandleError(err)
ddb := dynamodb.NewFromConfig(cfg, dbEsdkMiddleware.CreateMiddleware())

// 6. Put an item into our table using the above client.
Expand All @@ -146,9 +139,7 @@ func AwsKmsKeyringExample(kmsKeyID, ddbTableName string) {
Item: item,
}
_, err = ddb.PutItem(context.TODO(), putInput)
if err != nil {
panic(err)
}
utils.HandleError(err)

// 7. Get the item back from our table using the same client.
// The client will decrypt the item client-side, and return
Expand All @@ -168,9 +159,7 @@ func AwsKmsKeyringExample(kmsKeyID, ddbTableName string) {
ConsistentRead: aws.Bool(true),
}
result, err := ddb.GetItem(context.TODO(), getInput)
if err != nil {
panic(err)
}
utils.HandleError(err)
// Verify the decrypted item
if !reflect.DeepEqual(item, result.Item) {
panic("Decrypted item does not match original item")
Expand Down
49 changes: 11 additions & 38 deletions Examples/runtimes/go/keyring/rawaeskeyring.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package keyring

import (
"context"
"crypto/rand"
"fmt"
"reflect"

Expand All @@ -14,6 +13,7 @@ import (
dbesdkdynamodbencryptiontypes "github.com/aws/aws-database-encryption-sdk-dynamodb/awscryptographydbencryptionsdkdynamodbsmithygeneratedtypes"
dbesdkstructuredencryptiontypes "github.com/aws/aws-database-encryption-sdk-dynamodb/awscryptographydbencryptionsdkstructuredencryptionsmithygeneratedtypes"
"github.com/aws/aws-database-encryption-sdk-dynamodb/dbesdkmiddleware"
"github.com/aws/aws-database-encryption-sdk-dynamodb/examples/utils"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
Expand Down Expand Up @@ -45,32 +45,23 @@ import (
- Sort key is named "sort_key" with type (S)
*/

func RawAesExample(ddbTableName string) {
aesKeyBytes, err := generateAes256KeyBytes()
if err != nil {
panic(err)
}
func RawAesExample(ddbTableName, keyNamespace, keyName string, aesKeyBytes []byte) {
// Initialize the mpl client
matProv, err := mpl.NewClient(mpltypes.MaterialProvidersConfig{})
utils.HandleError(err)

// 1. Create the keyring.
// The DynamoDb encryption client uses this to encrypt and decrypt items.

// Initialize the mpl client
matProv, err := mpl.NewClient(mpltypes.MaterialProvidersConfig{})
if err != nil {
panic(err)
}
// Create the Raw Aes Keyring
var keyNamespace = "my-key-namespace"
var keyName = "my-aes-key-name"
rawAesKeyRingInput := mpltypes.CreateRawAesKeyringInput{
KeyName: keyName,
KeyNamespace: keyNamespace,
WrappingKey: aesKeyBytes,
WrappingAlg: mpltypes.AesWrappingAlgAlgAes256GcmIv12Tag16,
}
rawAesKeyring, err := matProv.CreateRawAesKeyring(context.Background(), rawAesKeyRingInput)
if err != nil {
panic(err)
}
utils.HandleError(err)
// 2. Configure which attributes are encrypted and/or signed when writing new items.
// For each attribute that may exist on the items we plan to write to our DynamoDbTable,
// we must explicitly configure how they should be treated during item encryption:
Expand Down Expand Up @@ -132,14 +123,10 @@ func RawAesExample(ddbTableName string) {

// Create DBESDK middleware
dbEsdkMiddleware, err := dbesdkmiddleware.NewDBEsdkMiddleware(listOfTableConfigs)
if err != nil {
panic(err)
}
utils.HandleError(err)
// Create aws config
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
panic(err)
}
utils.HandleError(err)
ddb := dynamodb.NewFromConfig(cfg, dbEsdkMiddleware.CreateMiddleware())

// 6. Put an item into our table using the above client.
Expand All @@ -155,9 +142,7 @@ func RawAesExample(ddbTableName string) {
Item: item,
}
_, err = ddb.PutItem(context.TODO(), putInput)
if err != nil {
panic(err)
}
utils.HandleError(err)
// 7. Get the item back from our table using the same client.
// The client will decrypt the item client-side, and return
// back the original item.
Expand All @@ -176,22 +161,10 @@ func RawAesExample(ddbTableName string) {
ConsistentRead: aws.Bool(true),
}
result, err := ddb.GetItem(context.TODO(), getInput)
if err != nil {
panic(err)
}
utils.HandleError(err)
// Verify the decrypted item
if !reflect.DeepEqual(item, result.Item) {
panic("Decrypted item does not match original item")
}
fmt.Println("Raw Aes Example successful.")
}

func generateAes256KeyBytes() ([]byte, error) {
key := make([]byte, 32) // 256 bits = 32 bytes
// Use crypto/rand for cryptographically secure random numbers
_, err := rand.Read(key)
if err != nil {
return nil, err
}
return key, nil
}
2 changes: 1 addition & 1 deletion Examples/runtimes/go/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ import (

func main() {
keyring.AwsKmsKeyringExample(utils.KmsKeyID(), utils.DdbTableName())
keyring.RawAesExample(utils.DdbTableName())
keyring.RawAesExample(utils.DdbTableName(), utils.KeyNamespace(), utils.KeyName(), utils.GenerateAes256KeyBytes())
}
30 changes: 30 additions & 0 deletions Examples/runtimes/go/utils/exampleUtils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@

package utils

import "crypto/rand"

const (
kmsKeyID = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"
ddbTableName = "DynamoDbEncryptionInterceptorTestTableCS"
keyNamespace = "my-key-namespace"
keyName = "my-key-name"
aesKeyBytes = 32 // 256 bits = 32 bytes
)

func KmsKeyID() string {
Expand All @@ -16,6 +21,14 @@ func DdbTableName() string {
return ddbTableName
}

func KeyNamespace() string {
return keyNamespace
}

func KeyName() string {
return keyName
}

func AreMapsEqual(map1, map2 map[string]string) bool {
if len(map1) != len(map2) {
return false
Expand All @@ -29,3 +42,20 @@ func AreMapsEqual(map1, map2 map[string]string) bool {
}
return true
}

func HandleError(err error) {
// Error handling is limited to panic for demonstration purposes only.
// In your code, errors should be properly handled.
if err != nil {
panic(err)
}
}

func GenerateAes256KeyBytes() []byte {
key := make([]byte, aesKeyBytes)
// crypto/rand is used here for demonstration.
// In your code, you should implement a key generation strategy that meets your security needs.
_, err := rand.Read(key)
HandleError(err)
return key
}
Loading