/
chacha20poly1305.go
51 lines (38 loc) · 1.29 KB
/
chacha20poly1305.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
package chacha20poly1305
import (
"errors"
"golang.org/x/crypto/chacha20poly1305"
)
var ErrInvalidParams = errors.New("chacha20poly1305: invalid params")
// Decrypt - decrypt without verify
func Decrypt(key32 []byte, nonce8 string, ciphertext []byte) ([]byte, error) {
return DecryptAndVerify(key32, nil, []byte(nonce8), ciphertext, nil)
}
// Encrypt - encrypt without seal
func Encrypt(key32 []byte, nonce8 string, plaintext []byte) ([]byte, error) {
return EncryptAndSeal(key32, nil, []byte(nonce8), plaintext, nil)
}
func DecryptAndVerify(key32, dst, nonce8, ciphertext, verify []byte) ([]byte, error) {
if len(key32) != chacha20poly1305.KeySize || len(nonce8) != 8 {
return nil, ErrInvalidParams
}
aead, err := chacha20poly1305.New(key32)
if err != nil {
return nil, err
}
nonce := make([]byte, chacha20poly1305.NonceSize)
copy(nonce[4:], nonce8)
return aead.Open(dst, nonce, ciphertext, verify)
}
func EncryptAndSeal(key32, dst, nonce8, plaintext, verify []byte) ([]byte, error) {
if len(key32) != chacha20poly1305.KeySize || len(nonce8) != 8 {
return nil, ErrInvalidParams
}
aead, err := chacha20poly1305.New(key32)
if err != nil {
return nil, err
}
nonce := make([]byte, chacha20poly1305.NonceSize)
copy(nonce[4:], nonce8)
return aead.Seal(dst, nonce, plaintext, verify), nil
}