/
encrypt_decrypt.go
101 lines (85 loc) · 1.93 KB
/
encrypt_decrypt.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Steve Phillips / elimisteve
// 2015.08.05
package cryptag
import (
"crypto/rand"
"fmt"
"golang.org/x/crypto/nacl/secretbox"
)
const (
validKeyLength = 32
)
var (
ErrDecrypt = fmt.Errorf("Error decrypting ciphertext")
ErrDecryptEmpty = fmt.Errorf("Error decrypting empty ciphertext")
ErrInvalidKey = fmt.Errorf("Invalid key")
ErrNilKey = fmt.Errorf("Nil key")
ErrNilNonce = fmt.Errorf("Nil nonce")
ErrInvalidNonce = fmt.Errorf("Invalid nonce")
)
func Encrypt(plain []byte, nonce *[24]byte, key *[32]byte) ([]byte, error) {
if nonce == nil {
return nil, ErrNilNonce
}
if key == nil {
return nil, ErrNilKey
}
cipher := secretbox.Seal(nil, plain, nonce, key)
return cipher, nil
}
func Decrypt(cipher []byte, nonce *[24]byte, key *[32]byte) ([]byte, error) {
if nonce == nil {
return nil, ErrNilNonce
}
if key == nil {
return nil, ErrNilKey
}
plain, ok := secretbox.Open(nil, cipher, nonce, key)
if !ok {
if len(cipher) == 0 {
return nil, ErrDecryptEmpty
}
return nil, ErrDecrypt
}
return plain, nil
}
func ConvertKey(key []byte) (goodKey *[32]byte, err error) {
if len(key) != validKeyLength {
return nil, fmt.Errorf("Invalid key; must be of length %d, has length %d",
validKeyLength, len(key))
}
// []byte -> *[32]byte
var good [validKeyLength]byte
copy(good[:], key)
return &good, nil
}
func UnconvertKey(goodKey *[32]byte) ([]byte, error) {
if goodKey == nil {
return nil, ErrNilKey
}
return (*goodKey)[:], nil
}
func ConvertNonce(nonce []byte) (goodNonce *[24]byte, err error) {
if len(nonce) != 24 {
return nil, ErrInvalidNonce
}
var b [24]byte
copy(b[:], nonce[:])
return &b, nil
}
func RandomNonce() (*[24]byte, error) {
var b [24]byte
_, err := rand.Reader.Read(b[:])
if err != nil {
return nil, err
}
return &b, nil
}
func RandomKey() (*[32]byte, error) {
var b [32]byte
_, err := rand.Reader.Read(b[:])
if err != nil {
return nil, err
}
return &b, nil
}