Newer
Older
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package userlib
import (
"fmt"
"strings"
"time"
"errors"
"log"
"io"
"crypto"
"crypto/rsa"
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"crypto/aes"
"crypto/cipher"
"golang.org/x/crypto/argon2"
"github.com/google/uuid"
)
type UUID = uuid.UUID
// RSA key size
var RSAKeySize = 2048
// AES block size and key size
var AESBlockSize = aes.BlockSize
var AESKeySize = 16
// Hash and MAC size
var HashSize = sha512.Size
// Debug print true/false
var DebugPrint = false
// DebugMsg. Helper function: Does formatted printing to stderr if
// the DebugPrint global is set. All our testing ignores stderr,
// so feel free to use this for any sort of testing you want.
func SetDebugStatus(status bool){
DebugPrint = status
}
func DebugMsg(format string, args ...interface{}) {
if DebugPrint {
msg := fmt.Sprintf("%v ", time.Now().Format("15:04:05.00000"))
log.Printf(msg+strings.Trim(format, "\r\n ")+"\n", args...)
}
}
// RandomBytes. Helper function: Returns a byte slice of the specificed
// size filled with random data
func RandomBytes(bytes int) (data []byte) {
data = make([]byte, bytes)
if _, err := io.ReadFull(rand.Reader, data); err != nil {
panic(err)
}
return
}
type PublicKeyType struct {
KeyType string
PubKey rsa.PublicKey
}
type PrivateKeyType struct {
KeyType string
PrivKey rsa.PrivateKey
}
// Datastore and Keystore variables
var datastore map[UUID][]byte = make(map[UUID][]byte)
var keystore map[string]PublicKeyType = make(map[string]PublicKeyType)
/*
********************************************
** Datastore Functions **
** DatastoreSet, DatastoreGet, **
** DatastoreDelete, DatastoreClear **
********************************************
*/
// Sets the value in the datastore
func DatastoreSet(key UUID, value []byte) {
foo := make([]byte, len(value))
copy(foo, value)
datastore[key] = foo
}
// Returns the value if it exists
func DatastoreGet(key UUID) (value []byte, ok bool) {
value, ok = datastore[key]
if ok && value != nil {
foo := make([]byte, len(value))
copy(foo, value)
return foo, ok
}
return
}
// Deletes a key
func DatastoreDelete(key UUID) {
delete(datastore, key)
}
// Use this in testing to reset the datastore to empty
func DatastoreClear() {
datastore = make(map[UUID][]byte)
}
// Use this in testing to reset the keystore to empty
func KeystoreClear() {
keystore = make(map[string]PublicKeyType)
}
// Sets the value in the keystore
func KeystoreSet(key string, value PublicKeyType) error {
_, present := keystore[key]
if present != false {
return errors.New("That entry in the Keystore has been taken.")
}
keystore[key] = value
return nil
}
// Returns the value if it exists
func KeystoreGet(key string) (value PublicKeyType, ok bool) {
value, ok = keystore[key]
return
}
// Use this in testing to get the underlying map if you want
// to play with the datastore.
func DatastoreGetMap() map[UUID][]byte {
return datastore
}
// Use this in testing to get the underlying map if you want
// to play with the keystore.
func KeystoreGetMap() map[string]PublicKeyType {
return keystore
}
/*
********************************************
** Public Key Encryption **
** PKEKeyGen, PKEEnc, PKEDec **
********************************************
*/
// Four structs to help you manage your different keys
// You should only have 1 of each struct
// keyType should be either:
// "PKE": encryption
// "DS": authentication and integrity
type PKEEncKey = PublicKeyType
type PKEDecKey = PrivateKeyType
type DSSignKey = PrivateKeyType
type DSVerifyKey = PublicKeyType
// Generates a key pair for public-key encryption via RSA
func PKEKeyGen() (PKEEncKey, PKEDecKey, error) {
RSAPrivKey, err := rsa.GenerateKey(rand.Reader, RSAKeySize)
RSAPubKey := RSAPrivKey.PublicKey
var PKEEncKeyRes PKEEncKey
PKEEncKeyRes.KeyType = "PKE"
PKEEncKeyRes.PubKey = RSAPubKey
var PKEDecKeyRes PKEDecKey
PKEDecKeyRes.KeyType = "PKE"
PKEDecKeyRes.PrivKey = *RSAPrivKey
return PKEEncKeyRes, PKEDecKeyRes, err
}
// Encrypts a byte stream via RSA-OAEP with sha512 as hash
func PKEEnc(ek PKEEncKey, plaintext []byte) ([]byte, error) {
RSAPubKey := &ek.PubKey
if ek.KeyType != "PKE" {
return nil, errors.New("Using a non-PKE key for PKE.")
}
ciphertext, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, RSAPubKey, plaintext, nil)
return ciphertext, err
}
// Decrypts a byte stream encrypted with RSA-OAEP/sha512
func PKEDec(dk PKEDecKey, ciphertext []byte) ([]byte, error) {
RSAPrivKey := &dk.PrivKey
if dk.KeyType != "PKE" {
return nil, errors.New("Using a non-PKE key for PKE.")
}
decryption, err := rsa.DecryptOAEP(sha512.New(), rand.Reader, RSAPrivKey, ciphertext, nil)
return decryption, err
}
/*
********************************************
** Digital Signature **
** DSKeyGen, DSSign, DSVerify **
********************************************
*/
// Generates a key pair for digital signature via RSA
func DSKeyGen() (DSSignKey, DSVerifyKey, error) {
RSAPrivKey, err := rsa.GenerateKey(rand.Reader, RSAKeySize)
RSAPubKey := RSAPrivKey.PublicKey
var DSSignKeyRes DSSignKey
DSSignKeyRes.KeyType = "DS"
DSSignKeyRes.PrivKey = *RSAPrivKey
var DSVerifyKeyRes DSVerifyKey
DSVerifyKeyRes.KeyType = "DS"
DSVerifyKeyRes.PubKey = RSAPubKey
return DSSignKeyRes, DSVerifyKeyRes, err
}
// Signs a byte stream via SHA256 and PKCS1v15
func DSSign(sk DSSignKey, msg []byte) ([]byte, error) {
RSAPrivKey := &sk.PrivKey
if sk.KeyType != "DS" {
return nil, errors.New("Using a non-DS key for DS.")
}
hashed := sha512.Sum512(msg)
sig, err := rsa.SignPKCS1v15(rand.Reader, RSAPrivKey, crypto.SHA512, hashed[:])
return sig, err
}
// Verifies a signature signed with SHA256 and PKCS1v15
func DSVerify(vk DSVerifyKey, msg []byte, sig []byte) error {
RSAPubKey := &vk.PubKey
if vk.KeyType != "DS" {
return errors.New("Using a non-DS key for DS.")
}
hashed := sha512.Sum512(msg)
err := rsa.VerifyPKCS1v15(RSAPubKey, crypto.SHA512, hashed[:], sig)
return err
}
/*
********************************************
** HMAC **
** HMACEval, HMACEqual **
********************************************
*/
// Evaluate the HMAC using sha512
func HMACEval(key []byte, msg []byte) ([]byte, error) {
if len(key) != 16 && len(key) != 24 && len(key) != 32 {
panic(errors.New("The input as key for HMAC should be a 16-byte key."))
}
mac := hmac.New(sha512.New, key)
mac.Write(msg)
res := mac.Sum(nil)
return res, nil
}
// Equals comparison for hashes/MACs
// Does NOT leak timing.
func HMACEqual(a []byte, b []byte) bool {
return hmac.Equal(a, b)
}
/*
********************************************
** KDF **
** Argon2Key **
********************************************
*/
// Argon2: Automatically choses a decent combination of iterations and memory
// Use this to generate a key from a password
func Argon2Key(password []byte, salt []byte, keyLen uint32) []byte {
return argon2.IDKey(password, salt, 1, 64*1024, 4, keyLen)
}
/*
********************************************
** Symmetric Encryption **
** SymEnc, SymDec **
********************************************
*/
// Encrypts a byte slice with AES-CTR
// Length of iv should be == AESBlockSize
func SymEnc(key []byte, iv []byte, plaintext []byte) []byte {
if len(iv) != AESBlockSize {
panic("IV length not equal to AESBlockSize")
}
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
stream := cipher.NewCTR(block, iv)
ciphertext := make([]byte, AESBlockSize + len(plaintext))
copy(ciphertext[:AESBlockSize], iv)
stream.XORKeyStream(ciphertext[AESBlockSize:], plaintext)
return ciphertext
}
// Decrypts a ciphertext encrypted with AES-CTR
func SymDec(key []byte, ciphertext []byte) []byte {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
iv := ciphertext[:AESBlockSize]
plaintext := make([]byte, len(ciphertext) - AESBlockSize)
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(plaintext, ciphertext[aes.BlockSize:])
return plaintext
}