-
Notifications
You must be signed in to change notification settings - Fork 0
/
iocrypt.go
233 lines (197 loc) · 6.06 KB
/
iocrypt.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// iocrypt - Encrypt/Decrypt io streams using AES/GCM
//
// This library encrypts and decrypts I/O streams using the standard lib
// AES/GCM golang libraries (in contrast to the standard libraries which
// operate on slices of bytes and are unsuitable for direct use with large data
// sets.)
//
// IMPORTANT DISCLAIMER:
//
// I'm NOT a cryptographer and I've put together this in an afternoon. It uses
// the standard libraries to encrypt/decrypt a file in "chunks", so it should be
// safe. Use at your own risk.
//
// (C) 2017 by Marco Paganini <paganini@paganini.net>
package iocrypt
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/binary"
"fmt"
"hash/crc32"
"io"
)
const (
// readChunkSize defines the size of the read buffer (in bytes).
readChunkSize = 64 * (1 << 20)
// sizeLen holds the length of the field in the header (in bytes).
sizeLen = 8
)
// Encrypt encrypts data from an io.Reader into an io.Writer using the
// specified key, and returns the number of bytes written to the io.Writer.
func Encrypt(r io.Reader, w io.Writer, key []byte) (int, error) {
block, err := aes.NewCipher(key)
if err != nil {
return 0, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return 0, err
}
// Create a random nonce.
nonce, err := randomBytes(gcm.NonceSize())
if err != nil {
return 0, err
}
payload := make([]byte, readChunkSize)
tbytes := 0
for {
// Reset payload slice to original size.
payload = payload[:readChunkSize]
nbytes, err := io.ReadFull(r, payload)
if err == io.EOF {
break
}
if err != nil && err != io.ErrUnexpectedEOF {
return 0, err
}
payload = payload[:nbytes]
payload = gcm.Seal(payload[:0], nonce, payload, nil)
// write header.
header := packNonceAndSize(nonce, len(payload))
written, err := w.Write(header)
if err != nil {
return 0, err
}
tbytes += written
// write payload.
written, err = w.Write(payload)
if err != nil {
return 0, err
}
tbytes += written
// Increment nonce to avoid nonce duplications on next chunk
incNonce(nonce)
}
return tbytes, nil
}
// Decrypt decrypts an encrypted data stream from an io.Reader into an
// io.Writer using the specified key, and returns the number of bytes written
// to the io.Writer.
func Decrypt(r io.Reader, w io.Writer, key []byte) (int, error) {
return DecryptN(r, w, key, 0)
}
// DecryptN decrypts an encrypted data stream from an io.Reader into an
// io.Writer using the specified key, and returns the number of bytes written
// to the io.Writer. The maximum length limits the number of bytes to read from
// the input stream (including the encryption block headers.) If the maximum
// length is set to zero, the function consumes all bytes in the input stream.
// Nonces are read from the input stream.
func DecryptN(r io.Reader, w io.Writer, key []byte, maxlen int) (int, error) {
block, err := aes.NewCipher(key)
if err != nil {
return 0, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return 0, err
}
header := make([]byte, gcm.NonceSize()+sizeLen+crc32.Size)
rbytes := 0
wbytes := 0
for {
// Break if we don't have enough bytes left to read the next header.
if maxlen > 0 && rbytes+len(header) > maxlen {
break
}
// Read header. When decrypting we need to read the header first to
// allocate the buffer for the encrypted payload following the header.
// It's not acceptable to have a short read in the header, so any error
// (other than EOF) causes the function to return.
nbytes, err := io.ReadFull(r, header)
if err == io.EOF {
break
}
if err != nil {
return 0, err
}
rbytes += nbytes
nonce, payloadLen, err := unpackNonceAndSize(header, gcm.NonceSize())
if err != nil {
return 0, err
}
// Break if we don't have enough bytes left to read the next payload block.
if maxlen > 0 && rbytes+payloadLen > maxlen {
break
}
// Allocate buffer and decrypt payload.
payload := make([]byte, payloadLen)
nbytes, err = io.ReadFull(r, payload)
if err != nil {
return 0, err
}
payload, err = gcm.Open(payload[:0], nonce, payload, nil)
if err != nil {
return 0, err
}
rbytes += nbytes
// Write payload.
written, err := w.Write(payload)
if err != nil {
return 0, err
}
wbytes += written
}
// If we have a specified maxlen, the number of read bytes must match exactly.
if maxlen > 0 && rbytes != maxlen {
return 0, fmt.Errorf("decoded %d bytes. Expected %d", rbytes, maxlen)
}
return wbytes, nil
}
// RandomAES128Key returns a randomly generated AES128 key.
func RandomAES128Key() ([]byte, error) {
return randomBytes(16)
}
// RandomAES256Key returns a randomly generated AES256 key.
func RandomAES256Key() ([]byte, error) {
return randomBytes(32)
}
// packNonceAndSize packs the nonce, size and their CRC32 into a byte slice.
func packNonceAndSize(nonce []byte, size int) []byte {
nlen := len(nonce)
sizeoffset := nlen
crcoffset := sizeoffset + sizeLen
ret := make([]byte, nlen+sizeLen+crc32.Size)
copy(ret, nonce)
binary.LittleEndian.PutUint64(ret[sizeoffset:], uint64(size))
crc := crc32.ChecksumIEEE(ret[0:crcoffset])
binary.LittleEndian.PutUint32(ret[crcoffset:], crc)
return ret
}
// unpackNonceAndSize retrieves the nonce and size from a byte slice.
// Returns an error if the checksum of nonce+size does not match.
func unpackNonceAndSize(b []byte, nonceSize int) ([]byte, int, error) {
nonce := b[0:nonceSize]
crcoffset := nonceSize + sizeLen
size := binary.LittleEndian.Uint64(b[nonceSize:crcoffset])
crc := crc32.ChecksumIEEE(b[0:crcoffset])
hcrc := binary.LittleEndian.Uint32(b[crcoffset:])
if crc != hcrc {
return nil, 0, fmt.Errorf("corrupt header or not an encrypted file. Got CRC %x, expected %x", hcrc, crc)
}
return nonce, int(size), nil
}
// incNonce increments the nonce (not the counter) by one.
func incNonce(nonce []byte) {
n := binary.LittleEndian.Uint64(nonce) + 1
binary.LittleEndian.PutUint64(nonce, n)
}
// randomBytes returns a byte slice of random bytes.
func randomBytes(n int) ([]byte, error) {
ret := make([]byte, n)
if _, err := io.ReadFull(rand.Reader, ret); err != nil {
return []byte{}, err
}
return ret, nil
}