-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryption.go
More file actions
513 lines (399 loc) · 11.7 KB
/
encryption.go
File metadata and controls
513 lines (399 loc) · 11.7 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package mppj
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"math/big"
"crypto/elliptic"
"crypto/hkdf"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"sync"
"golang.org/x/crypto/blake2b"
)
var curve = elliptic.P256()
// *********************** Constants ************************
// KeySize is the size of symmetric keys in bytes.
const KeySize = 16
// MaxValueSize is the maximum size of the input tables' values in bytes.
const MaxValueSize = 30
var zeroNonce = make([]byte, aes.BlockSize)
// *********************** Types ************************
type publicKey point
func (pk *publicKey) String() string {
pb, _ := pk.p.MarshalBinary()
return hex.EncodeToString(pb)
}
type secretKey scalar
type SymmetricCiphertext []byte
type SecretKey struct {
bsk *secretKey
esk *secretKey
}
type PublicKey struct {
bpk *publicKey
epk *publicKey
}
func KeyGen() (SecretKey, PublicKey) {
bsk, bpk := keyGenPKE()
esk, epk := keyGenPKE()
rsk := SecretKey{
bsk: bsk,
esk: esk,
}
rpk := PublicKey{
bpk: bpk,
epk: epk,
}
return rsk, rpk
}
func (pkt *PublicKey) String() string {
return fmt.Sprintf("bpk: %v,\nepk: %v", pkt.bpk, pkt.epk)
}
// message represents a message point on the elliptic curve.
type message struct {
m point
}
// Ciphertext represents an ElGamal ciphertext. c0 = g^r, c1 = m * pk^r
type Ciphertext struct {
c0 *point // g^r
c1 *point // m * pk^r
}
// pad pads the input byte slice to the next multiple of blockSize.
func pad(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
if padding == 0 {
padding = blockSize
}
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
// unpad removes the padding from the input byte slice.
func unpad(data []byte) ([]byte, error) {
if len(data) == 0 {
return nil, errors.New("invalid padding size, empty data")
}
padding := int(data[len(data)-1])
if padding > len(data) || padding == 0 {
return nil, errors.New("invalid padding size")
}
for _, v := range data[len(data)-padding:] {
if int(v) != padding {
return nil, errors.New("invalid padding")
}
}
return data[:len(data)-padding], nil
}
// *********************** PKE ************************
// encryptPKE encrypts a message msg using the public key pk.
func encryptPKE(pk *publicKey, msg *message) *Ciphertext {
r := randomScalar()
c0 := baseExp(r)
c1 := mul(&msg.m, (*point)(pk).scalarExp(r))
return &Ciphertext{
c0: c0,
c1: c1,
}
}
// encryptVectorPKE encrypts a byte slice PAYLOADSIZE bytes at a time using the public key pk. ( due to the 256-bit curve)
func encryptVectorPKE(pk *publicKey, msg []byte) ([]*Ciphertext, error) {
ciphertexts := make([]*Ciphertext, len(pad(msg, MaxValueSize))/MaxValueSize)
msg_padded := pad(msg, MaxValueSize)
for i := 0; i < len(msg_padded); i += MaxValueSize {
end := i + MaxValueSize
chunk := make([]byte, MaxValueSize)
copy(chunk, msg_padded[i:end])
idx := i / MaxValueSize
msg, err := newMessageFromBytes(chunk)
if err != nil {
return nil, err
}
ciphertexts[idx] = encryptPKE(pk, msg)
}
return ciphertexts, nil
}
// decryptPKE decrypts a ciphertext using the secret key sk.
func decryptPKE(sk *secretKey, ciphertext *Ciphertext) *message {
// Calculate s = (g ^ r) ^ -sk
s := ciphertext.c0.scalarExp((*scalar)(sk))
m := mul(ciphertext.c1, s)
return &message{m: *m}
}
// decryptVectorPKE decrypts a slice of ciphertexts using the secret key sk.
func decryptVectorPKE(sk *secretKey, ciphertexts []*Ciphertext) ([]byte, error) {
msgBytes := make([]byte, 0)
msgByteshelper := make([][]byte, len(ciphertexts))
var wg sync.WaitGroup
errCh := make(chan error, len(ciphertexts))
for i, ct := range ciphertexts {
wg.Add(1)
go func(i int, ct *Ciphertext) {
defer wg.Done()
msg, err := decryptPKE(sk, ct).GetMessageBytes()
if err != nil {
errCh <- err
return
}
msgByteshelper[i] = msg
}(i, ct)
}
wg.Wait()
close(errCh)
// Check for errors
if len(errCh) > 0 {
return nil, <-errCh
}
for _, msg := range msgByteshelper {
msgBytes = append(msgBytes, msg...)
}
msgBytes, err := unpad(msgBytes) // hom. PKE cannot be CCA secure anyway, so padding oracles are not a concern
if err != nil {
return nil, err
}
return msgBytes, nil
}
// reRand re-randomizes a ciphertext using pk.
func reRand(pk *publicKey, ciphertext *Ciphertext) *Ciphertext {
r := randomScalar()
c0 := mul(ciphertext.c0, baseExp(r))
c1 := mul(ciphertext.c1, (*point)(pk).scalarExp(r))
return &Ciphertext{
c0: c0,
c1: c1,
}
}
// reRandVector re-randomizes a slice of ciphertexts using pk.
func reRandVector(pk *publicKey, ciphertexts []*Ciphertext) []*Ciphertext {
ciphertextsout := make([]*Ciphertext, len(ciphertexts))
var wg sync.WaitGroup
for i, ct := range ciphertexts {
wg.Add(1)
go func(i int, ct *Ciphertext) {
defer wg.Done()
ciphertextsout[i] = reRand(pk, ct)
}(i, ct)
}
wg.Wait()
return ciphertextsout
}
// keyGenPKE generates a new public/private key pair. (scalar, point)
func keyGenPKE() (*secretKey, *publicKey) {
sk := randomScalar()
pk := baseExp(sk)
return (*secretKey)(sk.neg()), (*publicKey)(pk) // Negate the scalar for efficiency
}
// Serialize serializes a Ciphertext into a byte slice.
func (ct *Ciphertext) Serialize() ([]byte, error) {
c0Bytes, err := ct.c0.MarshalBinary()
if err != nil {
return nil, err
}
c1Bytes, err := ct.c1.MarshalBinary()
if err != nil {
return nil, err
}
return append(c0Bytes, c1Bytes...), nil
}
func serializeCiphertexts(cts []*Ciphertext) ([]byte, error) {
serialized := make([]byte, 0)
for _, ct := range cts {
serializedct, err := ct.Serialize()
if err != nil {
return nil, err
}
serialized = append(serialized, serializedct...)
}
return serialized, nil
}
// deserializeCiphertexts deserializes a byte slice into a slice of Ciphertexts.
func deserializeCiphertexts(data []byte) ([]*Ciphertext, error) {
byteLen := int(group.Params().CompressedElementLength)
ciphertextlen := 2 * byteLen
if len(data)%(ciphertextlen) != 0 {
return nil, errors.New("invalid byte slice length for deserialization of array")
}
ciphertexts := make([]*Ciphertext, 0)
for i := 0; i < len(data); i += ciphertextlen {
ciphertext, err := DeserializeCiphertext(data[i : i+ciphertextlen])
if err != nil {
return nil, err
}
ciphertexts = append(ciphertexts, ciphertext)
}
return ciphertexts, nil
}
// DeserializeCiphertext deserializes a byte slice into a Ciphertext.
func DeserializeCiphertext(data []byte) (*Ciphertext, error) {
byteLen := int(group.Params().CompressedElementLength)
pointLen := 2 * byteLen
if len(data) != pointLen {
return nil, errors.New("invalid byte slice length for deserialization")
}
c0 := newPoint()
c1 := newPoint()
err := c0.UnmarshalBinary(data[:byteLen])
if err != nil {
return nil, err
}
err = c1.UnmarshalBinary(data[byteLen:])
if err != nil {
return nil, err
}
return &Ciphertext{
c0: c0,
c1: c1,
}, nil
}
func (msg *message) String() string {
msgstr, err := msg.GetMessageString()
if err != nil {
return "Invalid message"
}
return fmt.Sprintf("Message(%s)", msgstr)
}
func (msg *message) Equals(other *message) bool {
if msg == nil || other == nil {
return msg == other
}
return msg.m.Equals(&other.m)
}
// Equals checks if two Ciphertexts are equal.
func (ct *Ciphertext) Equals(other *Ciphertext) bool {
if ct == nil || other == nil {
return ct == other
}
return ct.c0.Equals(other.c0) && ct.c1.Equals(other.c1)
}
func newMessageFromBytes(msgBytesin []byte) (*message, error) {
params := curve.Params()
if len(msgBytesin) == 0 {
return nil, errors.New("Empty message unsupported")
}
msgBytes := make([]byte, len(msgBytesin))
copy(msgBytes, msgBytesin)
// Prefix msgInt with one LSB byte
msgBytes = append(msgBytes, 0x02) // Prefix LSB byte
msgBytes = append([]byte{0x04}, msgBytes...) // Postfix MSB byte
msgInt := new(big.Int).SetBytes(msgBytes)
i := 1
y := new(big.Int)
for {
// adapted from elliptic.polynomial
x3 := new(big.Int).Mul(msgInt, msgInt)
x3.Mul(x3, msgInt)
threeX := new(big.Int).Lsh(msgInt, 1)
threeX.Add(threeX, msgInt)
x3.Sub(x3, threeX)
x3.Add(x3, params.B)
x3.Mod(x3, params.P)
// Try to calculate the square root mod p (y = sqrt(y^2) mod p)
y = new(big.Int).ModSqrt(x3, params.P)
if y != nil {
break
}
if i == 255 { // there is only one byte of space for the counter
return nil, errors.New("Failed to find a valid message point")
}
i++
// Update msgInt for the next iteration if not valid
msgInt.Add(msgInt, big.NewInt(1))
}
pointBytes := elliptic.Marshal(curve, msgInt, y)
result := newPoint()
err := result.UnmarshalBinary(pointBytes)
if err != nil {
return nil, err // when using a compatible curve, this should never happen
}
return &message{m: *result}, nil
}
// GetMessageBytes returns the message as a byte slice.
func (msg *message) GetMessageBytes() ([]byte, error) {
serialized, err := msg.m.MarshalBinary()
if err != nil {
return nil, err
}
x, _ := elliptic.UnmarshalCompressed(curve, serialized)
if x == nil {
return nil, fmt.Errorf("failed to unmarshal message point")
}
msgBytes := x.Bytes()
msgBytes = msgBytes[1 : len(msgBytes)-1] // Remove the prefix and LSB
return msgBytes, nil
}
func (msg *message) GetMessageString() (string, error) {
bytes, err := msg.GetMessageBytes()
if err != nil {
return "", err
}
return string(bytes), nil
}
func (msg *message) GetMessageStringHex() (string, error) {
bytes, err := msg.GetMessageBytes()
if err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
// randomMsg creates a new random message point.
func randomMsg() (*message, error) {
randomPoint := randomPoint()
return &message{m: *randomPoint}, nil
}
// HashToPoint hashes a byte slice to a point on the curve. Uses the secure hash-to-group approach from the underlying group
func hashToMessage(msg, sid []byte) *message {
return &message{m: *hashToPoint(msg, sid)}
}
// *********************** Symmetric ************************
// randomKeyFromPoint generates a random 16-byte key from a random point on the curve
func randomKeyFromPoint(sid []byte) (*point, []byte) {
rp := randomPoint()
key, err := keyFromPoint(rp, sid)
if err != nil {
panic(err) // Random points are assumed to be "correct"
}
return rp, key
}
func keyFromPoint(rp *point, sid []byte) ([]byte, error) {
info := "ephemeral associated data val key"
serialized, err := rp.MarshalBinary()
if err != nil {
return nil, err
}
key, err := hkdf.Key(sha256.New, serialized, sid, info, KeySize)
if err != nil {
return nil, err
}
return key, nil
}
// ctr encrypts/decrypts the plaintext using AES-CTR with the given key and nonce.
func ctr(key, plaintext []byte) (SymmetricCiphertext, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, len(plaintext))
cipher.NewCTR(block, zeroNonce).XORKeyStream(ciphertext, plaintext) // nonce = 16 * 0x00 since each key is used only once
return ciphertext, nil
}
// Encrypt the plaintext bytes with the symmetric key using AES-CTR
func symmetricEncrypt(key []byte, plaintext []byte) (SymmetricCiphertext, error) {
return ctr(key, plaintext)
}
// Decrypt the ciphertext bytes with the symmetric key using AES-CTR
func symmetricDecrypt(key []byte, ciphertext SymmetricCiphertext) ([]byte, error) {
return ctr(key, ciphertext)
}
// Generates keys *deterministically* from a seed
func GetTestKeys(seed []byte) (SecretKey, PublicKey) {
xof, err := blake2b.NewXOF(blake2b.OutputLengthUnknown, seed)
if err != nil {
panic(err)
}
esk := &scalar{s: group.RandomScalar(xof)}
bsk := &scalar{s: group.RandomScalar(xof)}
rsk := SecretKey{esk: (*secretKey)(esk.neg()), bsk: (*secretKey)(bsk.neg())}
rpk := PublicKey{epk: (*publicKey)(baseExp(esk)), bpk: (*publicKey)(baseExp(bsk))}
return rsk, rpk
}