Skip to content

Commit

Permalink
Simplify AWS request building logic.
Browse files Browse the repository at this point in the history
Modify already instantiated {Encrypt,Decrypt}Input, instead of creating a new one.

Add KeyId field to DecryptRequest field when associatedData is not provided. For DecryptRequest, this field is optional, but specifying it is recommended and allows the service to ensure the intended key is used. See https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html.

PiperOrigin-RevId: 534330644
Change-Id: I774b7fce9eb52c3dacd016c0e01a652582abbf17
  • Loading branch information
chuckx authored and copybara-github committed May 23, 2023
1 parent 16ef63f commit 373378b
Showing 1 changed file with 8 additions and 18 deletions.
26 changes: 8 additions & 18 deletions integration/awskms/aws_kms_aead.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,23 +51,17 @@ func newAWSAEAD(keyURI string, kms kmsiface.KMSAPI) *AWSAEAD {

// Encrypt encrypts the plaintext with associatedData.
func (a *AWSAEAD) Encrypt(plaintext, associatedData []byte) ([]byte, error) {
ad := hex.EncodeToString(associatedData)
req := &kms.EncryptInput{
KeyId: aws.String(a.keyURI),
Plaintext: plaintext,
EncryptionContext: map[string]*string{"additionalData": &ad},
KeyId: aws.String(a.keyURI),
Plaintext: plaintext,
}
if ad == "" {
req = &kms.EncryptInput{
KeyId: aws.String(a.keyURI),
Plaintext: plaintext,
}
if ad := hex.EncodeToString(associatedData); ad != "" {
req.EncryptionContext = map[string]*string{"additionalData": &ad}
}
resp, err := a.kms.Encrypt(req)
if err != nil {
return nil, err
}

return resp.CiphertextBlob, nil
}

Expand All @@ -82,16 +76,12 @@ func (a *AWSAEAD) Encrypt(plaintext, associatedData []byte) ([]byte, error) {
//
// See https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id.
func (a *AWSAEAD) Decrypt(ciphertext, associatedData []byte) ([]byte, error) {
ad := hex.EncodeToString(associatedData)
req := &kms.DecryptInput{
KeyId: aws.String(a.keyURI),
CiphertextBlob: ciphertext,
EncryptionContext: map[string]*string{"additionalData": &ad},
KeyId: aws.String(a.keyURI),
CiphertextBlob: ciphertext,
}
if ad == "" {
req = &kms.DecryptInput{
CiphertextBlob: ciphertext,
}
if ad := hex.EncodeToString(associatedData); ad != "" {
req.EncryptionContext = map[string]*string{"additionalData": &ad}
}
resp, err := a.kms.Decrypt(req)
if err != nil {
Expand Down

0 comments on commit 373378b

Please sign in to comment.