forked from awsdocs/aws-doc-sdk-examples
/
DecryptDatav2.go
71 lines (58 loc) · 1.95 KB
/
DecryptDatav2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// snippet-start:[kms.go-v2.DecryptData]
package main
import (
"context"
b64 "encoding/base64"
"flag"
"fmt"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/kms"
)
// KMSDecryptAPI defines the interface for the Decrypt function.
// We use this interface to test the function using a mocked service.
type KMSDecryptAPI interface {
Decrypt(ctx context.Context,
params *kms.DecryptInput,
optFns ...func(*kms.Options)) (*kms.DecryptOutput, error)
}
// DecodeData decrypts some text that was encrypted with an AWS Key Management Service (AWS KMS) key (KMS key).
// Inputs:
// c is the context of the method call, which includes the AWS Region.
// api is the interface that defines the method call.
// input defines the input arguments to the service call.
// Output:
// If success, a DecryptOutput object containing the result of the service call and nil.
// Otherwise, nil and an error from the call to Decrypt.
func DecodeData(c context.Context, api KMSDecryptAPI, input *kms.DecryptInput) (*kms.DecryptOutput, error) {
return api.Decrypt(c, input)
}
func main() {
data := flag.String("d", "", "The encrypted data, as a string")
flag.Parse()
if *data == "" {
fmt.Println("You must supply the encrypted data as a string")
fmt.Println("-d DATA")
return
}
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
panic("configuration error, " + err.Error())
}
client := kms.NewFromConfig(cfg)
blob, err := b64.StdEncoding.DecodeString(*data)
if err != nil {
panic("error converting string to blob, " + err.Error())
}
input := &kms.DecryptInput{
CiphertextBlob: blob,
}
result, err := DecodeData(context.TODO(), client, input)
if err != nil {
fmt.Println("Got error decrypting data: ", err)
return
}
fmt.Println(string(result.Plaintext))
}
// snippet-end:[kms.go-v2.DecryptData]