-
Notifications
You must be signed in to change notification settings - Fork 15
/
secret.go
49 lines (42 loc) · 1.09 KB
/
secret.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
package secret
import (
"bytes"
"encoding/base64"
"io"
"github.com/gtank/cryptopasta"
"github.com/odpf/siren/pkg/errors"
)
type Crypto struct {
encryptionKey *[32]byte
}
func New(encryptionKey string) (*Crypto, error) {
secretKey := &[32]byte{}
if len(encryptionKey) < 32 {
return nil, errors.New("random hash should be 32 chars in length")
}
_, err := io.ReadFull(bytes.NewBufferString(encryptionKey), secretKey[:])
if err != nil {
return nil, err
}
return &Crypto{
encryptionKey: secretKey,
}, nil
}
func (sec *Crypto) Encrypt(str MaskableString) (MaskableString, error) {
cipher, err := cryptopasta.Encrypt([]byte(str), sec.encryptionKey)
if err != nil {
return "", err
}
return MaskableString(base64.StdEncoding.EncodeToString(cipher)), nil
}
func (sec *Crypto) Decrypt(str MaskableString) (MaskableString, error) {
encrypted, err := base64.StdEncoding.DecodeString(str.UnmaskedString())
if err != nil {
return "", err
}
decryptedToken, err := cryptopasta.Decrypt(encrypted, sec.encryptionKey)
if err != nil {
return "", err
}
return MaskableString(decryptedToken), nil
}