This repository has been archived by the owner on Oct 6, 2019. It is now read-only.
/
transit.go
79 lines (65 loc) · 1.57 KB
/
transit.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
package vault
import (
"encoding/base64"
"errors"
)
// encrypt given string with userTransitKey
func (auth AuthInfo) EncryptTransit(key string, plaintext string) (string, error) {
c := GetConfig()
// if no key is specified, use run-time defaults
if key == "" {
key = c.UserTransitKey
if key == "" {
return "", errors.New("No transit key specified")
}
}
client, err := auth.Client()
if err != nil {
return "", err
}
resp, err := client.Logical().Write(
c.TransitBackend+"/encrypt/"+key,
map[string]interface{}{
"plaintext": base64.StdEncoding.EncodeToString([]byte(plaintext)),
})
if err != nil {
return "", err
}
cipher, ok := resp.Data["ciphertext"].(string)
if !ok {
return "", errors.New("Failed type assertion of response to string")
}
return cipher, nil
}
// decrypt given cipher with userTransitKey
func (auth AuthInfo) DecryptTransit(key string, cipher string) (string, error) {
c := GetConfig()
// if no key is specified, use run-time defaults
if key == "" {
key = c.UserTransitKey
if key == "" {
return "", errors.New("No transit key specified")
}
}
client, err := auth.Client()
if err != nil {
return "", err
}
resp, err := client.Logical().Write(
c.TransitBackend+"/decrypt/"+key,
map[string]interface{}{
"ciphertext": cipher,
})
if err != nil {
return "", err
}
b64, ok := resp.Data["plaintext"].(string)
if !ok {
return "", errors.New("Failed type assertion of response to string")
}
rawbytes, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
return "", err
}
return string(rawbytes), nil
}