main.go
1.5 KB
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
package aes
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"io"
mrand "math/rand"
"time"
)
const (
keySize = 32
allowedRunes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
// RandomKey returns a randomly generated 32 bytes long key.
func RandomKey() (key []byte) {
mrand.Seed(time.Now().UnixNano())
key = make([]byte, keySize)
for i := range key {
key[i] = allowedRunes[mrand.Intn(len(allowedRunes))]
}
return key
}
// Encrypt encrypts plaintext with key and returns resulting bytes.
func Encrypt(plaintext, key []byte) ([]byte, error) {
if len(key) != keySize {
return nil, fmt.Errorf("key size invalid: %d, must be %d\n", len(key), keySize)
}
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
// Decrypt decrypts ciphertext with key and returns resulting bytes.
func Decrypt(ciphertext, key []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, ciphertext, nil)
}