-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrypto.go
43 lines (34 loc) · 790 Bytes
/
crypto.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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
)
type crypto struct {
gcm cipher.AEAD
}
func newCrypto(key []byte) (*crypto, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &crypto{gcm: gcm}, nil
}
func (c *crypto) encrypt(in []byte) ([]byte, error) {
nonce := make([]byte, c.gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
cipherText := c.gcm.Seal(nil, nonce, in, nil)
cipherText = append(nonce, cipherText...)
return cipherText, nil
}
func (c *crypto) decrypt(in []byte) ([]byte, error) {
nonce := in[:c.gcm.NonceSize()]
return c.gcm.Open(nil, nonce, in[c.gcm.NonceSize():], nil)
}