/
crypt.go
89 lines (70 loc) · 1.76 KB
/
crypt.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
80
81
82
83
84
85
86
87
88
89
package crypt
import (
"crypto/cipher"
"crypto/rand"
"errors"
"github.com/evdnx/unixmint/db"
"github.com/evdnx/unixmint/pkg/util"
"golang.org/x/crypto/chacha20poly1305"
)
var aeadCipher cipher.AEAD = nil
func getCipher() (cipher.AEAD, error) {
if aeadCipher != nil {
return aeadCipher, nil
}
aead, err := chacha20poly1305.NewX(Key())
if err != nil {
return nil, err
}
return aead, nil
}
func Key() []byte {
key, err := db.Read(db.AuthBucket, "crypto_key")
if err != nil {
return nil
}
return []byte(key)
}
func GenerateKey(length int) []byte {
key := make([]byte, length)
rand.Read(key)
return key
}
func Reset() {
aeadCipher = nil
}
// Encrypt encrypts a message
func Encrypt(message any) (string, error) {
msg := util.InterfaceToByte(message)
aead, err := getCipher()
if err != nil {
return "", err
}
// Select a random nonce, and leave capacity for the ciphertext.
nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(msg)+aead.Overhead())
if _, err := rand.Read(nonce); err != nil {
return "", err
}
// Encrypt the message and append the ciphertext to the nonce.
encryptedMsg := aead.Seal(nonce, nonce, msg, nil)
return string(encryptedMsg), nil
}
// Decrypt decrypts a message
func Decrypt(encryptedMessage any) (string, error) {
aead, err := getCipher()
if err != nil {
return "", err
}
byteMsg := util.InterfaceToByte(encryptedMessage)
if len(byteMsg) < aead.NonceSize() {
return "", errors.New("ciphertext too short")
}
// Split nonce and ciphertext.
nonce, ciphertext := byteMsg[:aead.NonceSize()], byteMsg[aead.NonceSize():]
// Decrypt the message and check it wasn't tampered with.
plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}