forked from keys-pub/keys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
box.go
37 lines (31 loc) · 1.07 KB
/
box.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
package keys
import (
"github.com/pkg/errors"
"golang.org/x/crypto/nacl/box"
)
// BoxSeal encrypts a message to a recipient.
func BoxSeal(b []byte, recipient *X25519PublicKey, sender *X25519Key) []byte {
nonce := Rand24()
return sealBox(b, nonce, recipient, sender)
}
func sealBox(b []byte, nonce *[24]byte, recipient *X25519PublicKey, sender *X25519Key) []byte {
encrypted := box.Seal(nil, b, nonce, recipient.Bytes32(), sender.PrivateKey())
return append(nonce[:], encrypted...)
}
// BoxOpen decrypts a message from a sender.
func BoxOpen(encrypted []byte, sender *X25519PublicKey, recipient *X25519Key) ([]byte, error) {
return openBox(encrypted, sender, recipient)
}
func openBox(encrypted []byte, sender *X25519PublicKey, recipient *X25519Key) ([]byte, error) {
if len(encrypted) < 24 {
return nil, errors.Errorf("not enough bytes")
}
var nonce [24]byte
copy(nonce[:], encrypted[:24])
encrypted = encrypted[24:]
b, ok := box.Open(nil, encrypted, &nonce, sender.Bytes32(), recipient.PrivateKey())
if !ok {
return nil, errors.Errorf("box open failed")
}
return b, nil
}