/
aws.go
89 lines (71 loc) · 1.69 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
package crypto
import (
b "encoding/base64"
"log"
a "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
awskms "github.com/aws/aws-sdk-go/service/kms"
"github.com/spf13/viper"
)
type aws struct {
client *session.Session
}
func init() {
Register("aws", newAWS)
}
func newAWS() Crypto {
return &aws{client: newSession()}
}
func newSession() *session.Session {
profile := viper.GetString("AWSprofileName")
if profile != "" {
sess, err := session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Profile: profile,
})
if err != nil {
log.Fatal(err)
}
return sess
}
region := viper.GetString("AWSlocationID")
sess, err := session.NewSession(&a.Config{
Region: a.String(region),
})
if err != nil {
log.Fatal(err)
}
return sess
}
func (im *aws) Encrypt(input []byte) ([]byte, error) {
keyID := viper.GetString("AWScryptoKeyID")
client := awskms.New(im.client)
params := &awskms.EncryptInput{
KeyId: a.String(keyID),
Plaintext: input,
}
req, resp := client.EncryptRequest(params)
err := req.Send()
if err != nil {
return nil, err
}
encodedCiphertext := make([]byte, b.StdEncoding.EncodedLen(len(resp.CiphertextBlob)))
b.StdEncoding.Encode(encodedCiphertext, resp.CiphertextBlob)
return encodedCiphertext, nil
}
func (im *aws) Decrypt(input []byte) ([]byte, error) {
text, err := b.StdEncoding.DecodeString(string(input))
if err != nil {
return nil, err
}
client := awskms.New(im.client)
params := &awskms.DecryptInput{
CiphertextBlob: []byte(text),
}
req, resp := client.DecryptRequest(params)
err = req.Send()
if err != nil {
return nil, err
}
return resp.Plaintext, nil
}