-
Notifications
You must be signed in to change notification settings - Fork 4
/
encryption.go
75 lines (61 loc) · 1.81 KB
/
encryption.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
package cutil
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
"os"
"strings"
"github.com/pkg/errors"
"projectforge.dev/projectforge/app/util"
)
var key string
func EncryptMessage(message string, logger util.Logger) (string, error) {
byteMsg := []byte(message)
block, err := aes.NewCipher(getKey(logger))
if err != nil {
return "", errors.Wrap(err, "could not create new cipher")
}
cipherText := make([]byte, aes.BlockSize+len(byteMsg))
iv := cipherText[:aes.BlockSize]
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
return "", errors.Wrap(err, "could not encrypt")
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], byteMsg)
return base64.StdEncoding.EncodeToString(cipherText), nil
}
func DecryptMessage(message string, logger util.Logger) (string, error) {
cipherText, err := base64.StdEncoding.DecodeString(message)
if err != nil {
return "", errors.Wrap(err, "could not base64 decode")
}
block, err := aes.NewCipher(getKey(logger))
if err != nil {
return "", errors.Wrap(err, "could not create new cipher")
}
if len(cipherText) < aes.BlockSize {
return "", errors.New("invalid ciphertext block size")
}
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(cipherText, cipherText)
return string(cipherText), nil
}
func getKey(logger util.Logger) []byte {
if key == "" {
env := strings.ReplaceAll(util.AppKey, "-", "_") + "_encryption_key"
key = os.Getenv(env)
if key == "" {
logger.Warnf("using default encryption key\nset environment variable [%s] to save sessions between restarts", env)
key = util.AppKey + "_secret"
}
for i := len(key); i < 16; i++ {
key += " "
}
key = key[:16]
}
return []byte(key)
}