-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathsecretbox.go
More file actions
62 lines (52 loc) · 1.1 KB
/
Copy pathsecretbox.go
File metadata and controls
62 lines (52 loc) · 1.1 KB
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
package keyring
import (
"crypto/rand"
"golang.org/x/crypto/nacl/secretbox"
)
// SecretKey for encrypting items.
type SecretKey *[32]byte
func randBytes(length int) []byte {
buf := make([]byte, length)
if _, err := rand.Read(buf); err != nil {
panic(err)
}
return buf
}
func rand24() *[24]byte {
b := randBytes(24)
var b24 [24]byte
copy(b24[:], b[:24])
return &b24
}
func rand32() *[32]byte {
b := randBytes(32)
var b32 [32]byte
copy(b32[:], b[:32])
return &b32
}
func bytes32(b []byte) *[32]byte {
if len(b) != 32 {
panic("not 32 bytes")
}
var b32 [32]byte
copy(b32[:], b)
return &b32
}
func secretBoxSeal(b []byte, secretKey SecretKey) []byte {
nonce := rand24()
encrypted := secretbox.Seal(nil, b, nonce, secretKey)
encrypted = append(nonce[:], encrypted...)
return encrypted
}
func secretBoxOpen(encrypted []byte, secretKey SecretKey) ([]byte, bool) {
if secretKey == nil {
return nil, false
}
if len(encrypted) < 24 {
return nil, false
}
var nonce [24]byte
copy(nonce[:], encrypted[:24])
encrypted = encrypted[24:]
return secretbox.Open(nil, encrypted, &nonce, secretKey)
}