-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws.go
120 lines (100 loc) · 2.6 KB
/
aws.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package nvault
import (
"encoding/base64"
"errors"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
)
// AwsCryptor ...
type AwsCryptor struct {
AwsConfig
}
// AwsConfig ...
type AwsConfig struct {
AwsKmsKeyID string
AwsRegion string
AwsAccessKeyID string
AwsSecretAccessKey string
}
// Encrypt ...
func (c *AwsCryptor) Encrypt(value interface{}) (interface{}, error) {
if c.AwsKmsKeyID == "" {
return nil, errors.New("missing Aws KMS Key ID")
}
strvalue := fmt.Sprintf("%v", value)
output, err := serviceAws(&c.AwsConfig).Encrypt(&kms.EncryptInput{
KeyId: aws.String(c.AwsKmsKeyID),
Plaintext: []byte(strvalue),
})
if err != nil {
return value, nil
}
encoded := base64.StdEncoding.EncodeToString(output.CiphertextBlob)
return encoded, nil
}
// Decrypt ...
func (c *AwsCryptor) Decrypt(value interface{}) (interface{}, error) {
strvalue := fmt.Sprintf("%v", value)
decoded, err := base64.StdEncoding.DecodeString(strvalue)
if err != nil {
return value, err
}
output, err := serviceAws(&c.AwsConfig).Decrypt(&kms.DecryptInput{
CiphertextBlob: decoded,
})
if err != nil {
return value, err
}
return string(output.Plaintext), nil
}
func serviceAws(c *AwsConfig) *kms.KMS {
config := &aws.Config{}
if c.AwsRegion != "" {
config.Region = &c.AwsRegion
}
if c.AwsAccessKeyID != "" && c.AwsSecretAccessKey != "" {
config.Credentials = createAwsCredentials(c)
}
return kms.New(session.New(config))
}
func createAwsCredentials(c *AwsConfig) *credentials.Credentials {
defaultProvider := defaults.RemoteCredProvider(
aws.Config{Region: &c.AwsRegion},
defaults.Handlers(),
)
envProvider := &credentials.EnvProvider{}
providers := []credentials.Provider{
defaultProvider,
envProvider,
}
if c.AwsAccessKeyID != "" && c.AwsSecretAccessKey != "" {
providers = append(providers, &credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: c.AwsAccessKeyID,
SecretAccessKey: c.AwsSecretAccessKey,
SessionToken: "",
ProviderName: "",
},
})
}
return credentials.NewChainCredentials(providers)
}
// WithAwsCredential ...
func WithAwsCredential(awsAccessKeyID, awsSecretAccessKey string) Option {
return func(c *Config) error {
c.AwsAccessKeyID = awsAccessKeyID
c.AwsSecretAccessKey = awsSecretAccessKey
return nil
}
}
// WithAwsRegion ...
func WithAwsRegion(awsRegion string) Option {
return func(c *Config) error {
c.AwsRegion = awsRegion
return nil
}
}