-
Notifications
You must be signed in to change notification settings - Fork 0
/
alg_family_chacha20.go
104 lines (89 loc) · 2.13 KB
/
alg_family_chacha20.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package gfc
// This file provides (X)ChaCha20-Poly1305 encryption for gfc.
import (
"bytes"
"crypto/cipher"
"crypto/rand"
"github.com/pkg/errors"
"golang.org/x/crypto/chacha20poly1305"
)
func EncryptFamilyChaCha20(
newCipherFunc func([]byte) (cipher.AEAD, error),
nonceSize int,
plaintext Buffer,
key []byte,
) (
Buffer,
error,
) {
key, salt, err := keySaltPBKDF2(key, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to get key and salt with PBKDF2")
}
block, err := newCipherFunc(key)
if err != nil {
return nil, errors.Wrap(err, ErrNewCipherXChaCha20Poly1305.Error())
}
nonce := make([]byte, nonceSize)
rand.Read(nonce)
return formatOutputGfcSymm(
block.Seal(nil, nonce, plaintext.Bytes(), nil),
nonce,
salt,
)
}
func DecryptFamilyChaCha20(
newCipherFunc func([]byte) (cipher.AEAD, error),
nonceSize int,
ciphertext Buffer,
key []byte,
) (
Buffer,
error,
) {
_, ciphertextBytes, key, nonce, err := decodeOutputGfcSymm(ciphertext, key, nonceSize)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal gfc symmAEAD format")
}
block, err := newCipherFunc(key)
if err != nil {
return nil, errors.Wrap(err, ErrNewCipherXChaCha20Poly1305.Error())
}
plaintext, err := block.Open(nil, nonce, ciphertextBytes, nil)
if err != nil {
return nil, errors.Wrap(err, ErrOpenXChaCha20Poly1305.Error())
}
return bytes.NewBuffer(plaintext), nil
}
func EncryptXChaCha20Poly1305(plaintext Buffer, key []byte) (Buffer, error) {
return EncryptFamilyChaCha20(
chacha20poly1305.NewX,
chacha20poly1305.NonceSizeX,
plaintext,
key,
)
}
func DecryptXChaCha20Poly1305(ciphertext Buffer, key []byte) (Buffer, error) {
return DecryptFamilyChaCha20(
chacha20poly1305.NewX,
chacha20poly1305.NonceSizeX,
ciphertext,
key,
)
}
func EncryptChaCha20Poly1305(plaintext Buffer, key []byte) (Buffer, error) {
return EncryptFamilyChaCha20(
chacha20poly1305.New,
chacha20poly1305.NonceSize,
plaintext,
key,
)
}
func DecryptChaCha20Poly1305(ciphertext Buffer, key []byte) (Buffer, error) {
return DecryptFamilyChaCha20(
chacha20poly1305.New,
chacha20poly1305.NonceSize,
ciphertext,
key,
)
}