-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt.go
40 lines (36 loc) · 1.11 KB
/
encrypt.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
package neo
import (
"encoding/base64"
"fmt"
"os"
"github.com/google/tink/go/aead"
"github.com/google/tink/go/insecurecleartextkeyset"
"github.com/google/tink/go/keyset"
)
// Encrypter encrypts the given string.
type Encrypter func(s string) (string, error)
// NewEncrypter creates an encryption function from the JSON encryption key at the given filepath.
func NewEncrypter(jsonPath string) (Encrypter, error) {
f, err := os.Open(jsonPath)
if err != nil {
return nil, fmt.Errorf("neo: failed to open the encryption key file: %w", err)
}
defer f.Close()
kh, err := insecurecleartextkeyset.Read(keyset.NewJSONReader(f))
if err != nil {
return nil, fmt.Errorf("neo: failed to read the encryption key file: %w", err)
}
a, err := aead.New(kh)
if err != nil {
return nil, fmt.Errorf("neo: failed to create an AEAD primitive: %w", err)
}
var empty []byte
return func(s string) (string, error) {
enc, err := a.Encrypt([]byte(s), empty)
if err != nil {
return "", fmt.Errorf("neo: failed to encrypt the given string: %w", err)
}
b64 := base64.StdEncoding.EncodeToString(enc)
return b64, nil
}, nil
}