| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
package awskms |
| 19 |
|
| 20 |
import ( |
| 21 |
"context" |
| 22 |
"encoding/hex" |
| 23 |
|
| 24 |
"github.com/aws/aws-sdk-go-v2/service/kms" |
| 25 |
"github.com/aws/aws-sdk-go-v2/aws" |
| 26 |
"github.com/tink-crypto/tink-go/v2/tink" |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
type awsAEAD struct { |
| 33 |
keyID string |
| 34 |
kms KMSAPI |
| 35 |
encryptionContextName EncryptionContextName |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
func NewAEADWithContext(ctx context.Context, keyID string, opts ...ClientOption) (tink.AEADWithContext, error) { |
| 41 |
keyURI := awsPrefix + keyID |
| 42 |
awsClient, err := newAWSClient(ctx, keyURI, opts...) |
| 43 |
if err != nil { |
| 44 |
return nil, err |
| 45 |
} |
| 46 |
return newAWSAEAD(keyID, awsClient.kms, awsClient.encryptionContextName), nil |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
func newAWSAEAD(keyID string, kms KMSAPI, name EncryptionContextName) *awsAEAD { |
| 57 |
return &awsAEAD{ |
| 58 |
keyID: keyID, |
| 59 |
kms: kms, |
| 60 |
encryptionContextName: name, |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
func (a *awsAEAD) EncryptWithContext(ctx context.Context, plaintext, associatedData []byte) ([]byte, error) { |
| 66 |
req := &kms.EncryptInput{ |
| 67 |
KeyId: aws.String(a.keyID), |
| 68 |
Plaintext: plaintext, |
| 69 |
} |
| 70 |
if len(associatedData) > 0 { |
| 71 |
ad := hex.EncodeToString(associatedData) |
| 72 |
req.EncryptionContext = map[string]string{a.encryptionContextName.String(): ad} |
| 73 |
} |
| 74 |
resp, err := a.kms.Encrypt(ctx, req) |
| 75 |
if err != nil { |
| 76 |
return nil, err |
| 77 |
} |
| 78 |
return resp.CiphertextBlob, nil |
| 79 |
} |
| 80 |
|
| 81 |
func (a *awsAEAD) Encrypt(plaintext, associatedData []byte) ([]byte, error) { |
| 82 |
return a.EncryptWithContext(context.TODO(), plaintext, associatedData) |
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
func (a *awsAEAD) DecryptWithContext(ctx context.Context, ciphertext, associatedData []byte) ([]byte, error) { |
| 87 |
req := &kms.DecryptInput{ |
| 88 |
KeyId: aws.String(a.keyID), |
| 89 |
CiphertextBlob: ciphertext, |
| 90 |
} |
| 91 |
if len(associatedData) > 0 { |
| 92 |
ad := hex.EncodeToString(associatedData) |
| 93 |
req.EncryptionContext = map[string]string{a.encryptionContextName.String(): ad} |
| 94 |
} |
| 95 |
resp, err := a.kms.Decrypt(ctx, req) |
| 96 |
if err != nil { |
| 97 |
return nil, err |
| 98 |
} |
| 99 |
return resp.Plaintext, nil |
| 100 |
} |
| 101 |
|
| 102 |
func (a *awsAEAD) Decrypt(ciphertext, associatedData []byte) ([]byte, error) { |
| 103 |
return a.DecryptWithContext(context.TODO(), ciphertext, associatedData) |
| 104 |
} |