-
Notifications
You must be signed in to change notification settings - Fork 0
/
security.go
52 lines (48 loc) · 1.41 KB
/
security.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
package task
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
"k8s.io/klog/v2"
"os"
)
// sessionKey is the environment variable for the session key.
var sessionKey = os.Getenv(SessionKey)
// Decrypt decrypts the content using the session key.
func Decrypt(content []byte) ([]byte, error) {
if len(sessionKey) == 0 {
return content, nil
} else {
key, _ := base64.StdEncoding.DecodeString(sessionKey)
ciphertext, _ := base64.StdEncoding.DecodeString(string(content))
c, _ := aes.NewCipher(key)
nonceSize := 16
gcm, _ := cipher.NewGCMWithNonceSize(c, nonceSize)
nonce, message := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, message, nil)
}
}
// Encrypt encrypts the content using the session key.
func Encrypt(content []byte) ([]byte, error) {
if len(sessionKey) == 0 {
return content, nil
} else {
key, _ := base64.StdEncoding.DecodeString(sessionKey)
c, _ := aes.NewCipher(key)
nonce := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
klog.Fatalf("Cannot encrypt data: [%v]", err)
return nil, err
}
gcm, err := cipher.NewGCMWithNonceSize(c, 16)
if err != nil {
klog.Fatalf("Cannot encrypt data: [%v]", err)
return nil, err
}
encryptedBytes := gcm.Seal(nil, nonce, content, nil)
ciphertext := base64.StdEncoding.EncodeToString(append(nonce, encryptedBytes...))
return []byte(ciphertext), nil
}
}