-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcrypto.go
69 lines (60 loc) · 1.37 KB
/
crypto.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
package macaroon
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"fmt"
"hash"
"code.google.com/p/go.crypto/nacl/secretbox"
)
func keyedHash(key, text []byte) []byte {
h := keyedHasher(key)
h.Write([]byte(text))
return h.Sum(nil)
}
func keyedHasher(key []byte) hash.Hash {
return hmac.New(sha256.New, key)
}
func makeKey(key []byte) *[keyLen]byte {
if len(key) < keyLen {
var h [keyLen]byte
copy(h[:], key)
return &h
}
h := sha256.Sum256(key)
return &h
}
const (
keyLen = 32
nonceLen = 24
)
func newNonce() (*[nonceLen]byte, error) {
var nonce [nonceLen]byte
_, err := rand.Read(nonce[:])
if err != nil {
return nil, fmt.Errorf("cannot generate random bytes: %v", err)
}
return &nonce, nil
}
func encrypt(key, text []byte) ([]byte, error) {
nonce, err := newNonce()
if err != nil {
return nil, err
}
out := make([]byte, 0, len(nonce)+secretbox.Overhead+len(text))
out = append(out, nonce[:]...)
return secretbox.Seal(out, text, nonce, makeKey(key)), nil
}
func decrypt(key, ciphertext []byte) ([]byte, error) {
if len(ciphertext) < nonceLen+secretbox.Overhead {
return nil, fmt.Errorf("message too short")
}
var nonce [nonceLen]byte
copy(nonce[:], ciphertext)
ciphertext = ciphertext[nonceLen:]
text, ok := secretbox.Open(nil, ciphertext, &nonce, makeKey(key))
if !ok {
return nil, fmt.Errorf("decryption failure")
}
return text, nil
}