/
nacl.go
47 lines (34 loc) · 1007 Bytes
/
nacl.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
package nacl
import (
"errors"
"io"
"golang.org/x/crypto/nacl/secretbox"
)
const nonceSize = 24
const secretKeySize = 32
func easyOpen(box, key []byte) ([]byte, error) {
var secretKey [secretKeySize]byte
if len(key) != secretKeySize {
return nil, errors.New("secretbox: key length must be 32")
}
if len(box) < nonceSize {
return nil, errors.New("secretbox: message too short")
}
decryptNonce := new([nonceSize]byte)
copy(decryptNonce[:], box[:nonceSize])
copy(secretKey[:], key)
decrypted, ok := secretbox.Open([]byte{}, box[nonceSize:], decryptNonce, &secretKey)
if !ok {
return nil, errors.New("secretbox: could not decrypt data with private key")
}
return decrypted, nil
}
func easySeal(message, key []byte, rand io.Reader) ([]byte, error) {
nonce := new([nonceSize]byte)
if _, err := rand.Read(nonce[:]); err != nil {
return nil, err
}
var secretKey [secretKeySize]byte
copy(secretKey[:], key)
return secretbox.Seal(nonce[:], message, nonce, &secretKey), nil
}