-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathnacl.go
71 lines (60 loc) · 1.43 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package nacl
import (
"bytes"
"crypto/rand"
"errors"
"io"
"io/ioutil"
"github.com/lucas-clemente/git-cr/git/repo"
"golang.org/x/crypto/nacl/secretbox"
)
type naclBackend struct {
backend repo.Backend
key [32]byte
}
// NewNaClBackend returns a repo.Backend implementation that encrypts data using nacl
func NewNaClBackend(backend repo.Backend, key [32]byte) repo.Backend {
return &naclBackend{
backend: backend,
key: key,
}
}
func (r *naclBackend) ReadBlob(name string) (io.ReadCloser, error) {
encryptedRdr, err := r.backend.ReadBlob(name + ".nacl")
if err != nil {
return nil, err
}
defer encryptedRdr.Close()
data, err := ioutil.ReadAll(encryptedRdr)
if err != nil {
return nil, err
}
if len(data) < 24 {
return nil, errors.New("encrypted message is too short")
}
var nonce [24]byte
copy(nonce[:], data)
data = data[24:]
out, ok := secretbox.Open([]byte{}, data, &nonce, &r.key)
if !ok {
return nil, errors.New("error verifying encrypted data")
}
return ioutil.NopCloser(bytes.NewBuffer(out)), nil
}
func (r *naclBackend) WriteBlob(name string, rdr io.Reader) error {
data, err := ioutil.ReadAll(rdr)
if err != nil {
return err
}
nonce := makeNonce()
out := secretbox.Seal(nonce[:], data, nonce, &r.key)
return r.backend.WriteBlob(name+".nacl", bytes.NewBuffer(out))
}
func makeNonce() *[24]byte {
var nonce [24]byte
_, err := rand.Read(nonce[:])
if err != nil {
panic(err)
}
return &nonce
}