/
encrypt.go
129 lines (101 loc) · 2.28 KB
/
encrypt.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package pg
import (
"crypto/aes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"errors"
"io"
"crypto/cipher"
)
const (
NonceSize = aes.BlockSize
MACSize = 32 // Output size of HMAC-SHA-256
CKeySize = 32 // Cipher key size - AES-256
MKeySize = 32 // HMAC key size - HMAC-SHA-256
)
var KeySize = CKeySize + MKeySize
var (
ErrEncrypt = errors.New("secret: encryption failed")
ErrDecrypt = errors.New("secret: decryption failed")
)
func pad(in []byte) []byte {
padding := aes.BlockSize - (len(in) % aes.BlockSize)
for i := 0; i < padding; i++ {
in = append(in, byte(padding))
}
return in
}
func unpad(in []byte) []byte {
if len(in) == 0 {
return nil
}
padding := in[len(in)-1]
if int(padding) > len(in) || padding > aes.BlockSize {
return nil
} else if padding == 0 {
return nil
}
for i := len(in) - 1; i > len(in)-int(padding)-1; i-- {
if in[i] != padding {
return nil
}
}
return in[:len(in)-int(padding)]
}
func randBytes(n int) ([]byte, error) {
r := make([]byte, n)
_, err := io.ReadFull(rand.Reader, r)
if err != nil {
return nil, err
}
return r, nil
}
func Encrypt(key, message []byte) ([]byte, error) {
if len(key) != KeySize {
return nil, ErrEncrypt
}
iv, err := randBytes(NonceSize)
if err != nil {
return nil, ErrEncrypt
}
pmessage := pad(message)
ct := make([]byte, len(pmessage))
c, _ := aes.NewCipher(key[:CKeySize])
ctr := cipher.NewCBCEncrypter(c, iv)
ctr.CryptBlocks(ct, pmessage)
h := hmac.New(sha256.New, key[CKeySize:])
ct = append(iv, ct...)
h.Write(ct)
ct = h.Sum(ct)
return ct, nil
}
func Decrypt(key, message []byte) ([]byte, error) {
if len(key) != KeySize {
return nil, ErrDecrypt
}
if (len(message) % aes.BlockSize) != 0 {
return nil, ErrDecrypt
}
if len(message) < (4 * aes.BlockSize) {
return nil, ErrDecrypt
}
macStart := len(message) - MACSize
tag := message[macStart:]
out := make([]byte, macStart-NonceSize)
message = message[:macStart]
h := hmac.New(sha256.New, key[CKeySize:])
h.Write(message)
mac := h.Sum(nil)
if !hmac.Equal(mac, tag) {
return nil, ErrDecrypt
}
c, _ := aes.NewCipher(key[:CKeySize])
ctr := cipher.NewCBCDecrypter(c, message[:NonceSize])
ctr.CryptBlocks(out, message[NonceSize:])
pt := unpad(out)
if pt == nil {
return nil, ErrDecrypt
}
return pt, nil
}