-
Notifications
You must be signed in to change notification settings - Fork 2
/
encryption.go
42 lines (32 loc) · 1.01 KB
/
encryption.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
package passtor
import (
"golang.org/x/crypto/chacha20poly1305"
)
const (
// NONCESIZE size in bytes for a nonce
NONCESIZE = chacha20poly1305.NonceSizeX
)
// Nonce format for encryption
type Nonce [NONCESIZE]byte
// EncryptedData generic format
type EncryptedData []byte
// Encrypt encrypts the given data under the given key using ChaCha20 stream cipher
func Encrypt(data []byte, key SymmetricKey) (EncryptedData, Nonce, error) {
cipher, err := chacha20poly1305.NewX(SymmetricKeyToBytes(key))
if err != nil {
return nil, Nonce{}, err
}
nonce, err := RandomBytes(chacha20poly1305.NonceSizeX)
if err != nil {
return nil, Nonce{}, err
}
return cipher.Seal(nil, nonce, data, nil), BytesToNonce(nonce), nil
}
// Decrypt decrypts the given ciphertext under the given key
func Decrypt(ciphertext []byte, nonce Nonce, key SymmetricKey) ([]byte, error) {
cipher, err := chacha20poly1305.NewX(SymmetricKeyToBytes(key))
if err != nil {
return nil, err
}
return cipher.Open(nil, NonceToBytes(nonce), ciphertext, nil)
}