This repository has been archived by the owner on Mar 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcore.rs
1224 lines (1004 loc) · 39.4 KB
/
core.rs
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
use super::super::big::Big;
use super::super::ecp::ECP;
use super::super::ecp2::ECP2;
use super::super::fp::FP;
use super::super::fp2::FP2;
use super::super::hash_to_curve::*;
use super::super::pair;
use super::super::rom::*;
use super::iso::{iso11_to_ecp, iso3_to_ecp2};
use errors::AmclError;
use hash256::HASH256;
use rand::RAND;
// Key Generation Constants
/// Domain for key generation.
pub const KEY_SALT: &[u8] = b"BLS-SIG-KEYGEN-SALT-";
/// L = ceil((3 * ceil(log2(r))) / 16) = 48.
pub const KEY_GENERATION_L: u8 = 48;
// Length of objects in bytes
/// The required number of bytes for a secret key
pub const SECRET_KEY_BYTES: usize = 32;
/// The required number of bytes for a compressed G1 point
pub const G1_BYTES: usize = MODBYTES;
/// The required number of bytes for a compressed G2 point
pub const G2_BYTES: usize = MODBYTES * 2;
// Serialization flags
const COMPRESION_FLAG: u8 = 0b_1000_0000;
const INFINITY_FLAG: u8 = 0b_0100_0000;
const Y_FLAG: u8 = 0b_0010_0000;
/// KeyGenerate
///
/// Generate a new Secret Key based off Initial Keying Material (IKM) and Key Info (salt).
/// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.3
pub(crate) fn key_generate(ikm: &[u8], key_info: &[u8]) -> [u8; SECRET_KEY_BYTES] {
// PRK = HKDF-Extract("BLS-SIG-KEYGEN-SALT-", IKM || I2OSP(0, 1))
let mut prk = Vec::<u8>::with_capacity(1 + ikm.len());
prk.extend_from_slice(ikm);
prk.push(0);
let prk = HASH256::hkdf_extract(KEY_SALT, &prk);
// OKM = HKDF-Expand(PRK, key_info || I2OSP(L, 2), L)
let mut info = key_info.to_vec();
info.extend_from_slice(&[0, KEY_GENERATION_L]);
let okm = HASH256::hkdf_extend(&prk, &info, KEY_GENERATION_L);
// SK = OS2IP(OKM) mod r
let r = Big::new_ints(&CURVE_ORDER);
let mut secret_key = Big::frombytes(&okm);
secret_key.rmod(&r);
secret_key_to_bytes(&secret_key)
}
// Converts secret key bytes to a Big
pub fn secret_key_from_bytes(secret_key: &[u8]) -> Result<Big, AmclError> {
if secret_key.len() != SECRET_KEY_BYTES {
return Err(AmclError::InvalidSecretKeySize);
}
// Prepend to MODBYTES in length
let mut secret_key_bytes = [0u8; MODBYTES];
secret_key_bytes[MODBYTES - SECRET_KEY_BYTES..].copy_from_slice(secret_key);
// Ensure secret key is in the range [0, r-1].
let secret_key = Big::frombytes(&secret_key_bytes);
if secret_key >= Big::new_ints(&CURVE_ORDER) {
return Err(AmclError::InvalidSecretKeyRange);
}
Ok(secret_key)
}
// Converts secret key Big to bytes
pub fn secret_key_to_bytes(secret_key: &Big) -> [u8; SECRET_KEY_BYTES] {
let mut big_bytes = [0u8; MODBYTES];
secret_key.tobytes(&mut big_bytes);
let mut secret_key_bytes = [0u8; SECRET_KEY_BYTES];
secret_key_bytes.copy_from_slice(&big_bytes[MODBYTES - SECRET_KEY_BYTES..]);
secret_key_bytes
}
// Verifies a G1 point is in subgroup `r`.
pub fn subgroup_check_g1(point: &ECP) -> bool {
let r = Big::new_ints(&CURVE_ORDER);
let check = pair::g1mul(&point, &r);
check.is_infinity()
}
// Verifies a G2 point is in subgroup `r`.
pub fn subgroup_check_g2(point: &ECP2) -> bool {
let r = Big::new_ints(&CURVE_ORDER);
let check = pair::g2mul(&point, &r);
check.is_infinity()
}
// Compare values of two FP2 elements,
// -1 if num1 < num2; 0 if num1 == num2; 1 if num1 > num2
fn zcash_cmp_fp2(num1: &mut FP2, num2: &mut FP2) -> isize {
// First compare FP2.b
let mut result = Big::comp(&num1.getb(), &num2.getb());
// If FP2.b is equal compare FP2.a
if result == 0 {
result = Big::comp(&num1.geta(), &num2.geta());
}
result
}
/// Take a G1 point (x, y) and compress it to a 48 byte array.
///
/// See https://github.com/zkcrypto/pairing/blob/master/src/bls12_381/README.md#serialization
pub fn serialize_g1(g1: &ECP) -> [u8; G1_BYTES] {
// Check point at inifinity
if g1.is_infinity() {
let mut result = [0u8; G1_BYTES];
// Set compressed flag and infinity flag
result[0] = u8::pow(2, 6) + u8::pow(2, 7);
return result;
}
// Convert x-coordinate to bytes
let mut result = [0u8; G1_BYTES];
g1.getx().tobytes(&mut result);
// Evaluate if y > -y
let mut tmp = g1.clone();
tmp.affine();
let y = tmp.gety();
tmp.neg();
let y_neg = tmp.gety();
// Set flags
if y > y_neg {
result[0] += Y_FLAG;
}
result[0] += COMPRESION_FLAG;
result
}
/// Take a G1 point (x, y) and converti it to a 96 byte array.
///
/// See https://github.com/zkcrypto/pairing/blob/master/src/bls12_381/README.md#serialization
pub fn serialize_uncompressed_g1(g1: &ECP) -> [u8; G1_BYTES * 2] {
// Check point at inifinity
let mut result = [0u8; G1_BYTES * 2];
if g1.is_infinity() {
result[0] = INFINITY_FLAG;
return result;
}
// Convert x-coordinate to bytes
g1.getx().tobytes(&mut result[..MODBYTES]);
g1.gety().tobytes(&mut result[MODBYTES..]);
result
}
/// Take a 48 or 96 byte array and convert to a G1 point (x, y)
///
/// See https://github.com/zkcrypto/pairing/blob/master/src/bls12_381/README.md#serialization
pub fn deserialize_g1(g1_bytes: &[u8]) -> Result<ECP, AmclError> {
if g1_bytes.len() == 0 {
return Err(AmclError::InvalidG1Size);
}
if g1_bytes[0] & COMPRESION_FLAG == 0 {
deserialize_uncompressed_g1(g1_bytes)
} else {
deserialize_compressed_g1(g1_bytes)
}
}
// Deserialization of a G1 point from x-coordinate
fn deserialize_compressed_g1(g1_bytes: &[u8]) -> Result<ECP, AmclError> {
// Length must be 48 bytes
if g1_bytes.len() != G1_BYTES {
return Err(AmclError::InvalidG1Size);
}
// Check infinity flag
if g1_bytes[0] & INFINITY_FLAG != 0 {
// Trailing bits should all be 0.
if g1_bytes[0] & 0b_0011_1111 != 0 {
return Err(AmclError::InvalidPoint);
}
for item in g1_bytes.iter().skip(1) {
if *item != 0 {
return Err(AmclError::InvalidPoint);
}
}
return Ok(ECP::new()); // infinity
}
let y_flag: bool = (g1_bytes[0] & Y_FLAG) > 0;
// Zero flags
let mut g1_bytes = g1_bytes.to_owned();
g1_bytes[0] = g1_bytes[0] & 0b_0001_1111;
let x = Big::frombytes(&g1_bytes);
// Require element less than field modulus
let m = Big::new_ints(&MODULUS);
if x >= m {
return Err(AmclError::InvalidPoint);
}
// Convert to G1 from x-coordinate
let point = ECP::new_big(&x);
if point.is_infinity() {
return Err(AmclError::InvalidPoint);
}
// Confirm y value
let mut point_neg = point.clone();
point_neg.neg();
if (point.gety() > point_neg.gety()) != y_flag {
Ok(point_neg)
} else {
Ok(point)
}
}
// Deserialization of a G1 point from (x, y).
fn deserialize_uncompressed_g1(g1_bytes: &[u8]) -> Result<ECP, AmclError> {
// Length must be 96 bytes
if g1_bytes.len() != G1_BYTES * 2 {
return Err(AmclError::InvalidG1Size);
}
// Check infinity flag
if g1_bytes[0] & INFINITY_FLAG != 0 {
// Trailing bits should all be 0.
if g1_bytes[0] & 0b_0011_1111 != 0 {
return Err(AmclError::InvalidPoint);
}
for item in g1_bytes.iter().skip(1) {
if *item != 0 {
return Err(AmclError::InvalidPoint);
}
}
return Ok(ECP::new()); // infinity
}
// Require y_flag to be zero
if (g1_bytes[0] & Y_FLAG) > 0 {
return Err(AmclError::InvalidYFlag);
}
// Zero flags
let mut g1_bytes = g1_bytes.to_owned();
g1_bytes[0] = g1_bytes[0] & 0b_0001_1111;
let x = Big::frombytes(&g1_bytes[..MODBYTES]);
let y = Big::frombytes(&g1_bytes[MODBYTES..]);
// Require elements less than field modulus
let m = Big::new_ints(&MODULUS);
if x >= m || y >= m {
return Err(AmclError::InvalidPoint);
}
// Convert to G1
let point = ECP::new_bigs(&x, &y);
if point.is_infinity() {
return Err(AmclError::InvalidPoint);
}
Ok(point)
}
/// Take a G2 point (x, y) and compress it to a 96 byte array as the x-coordinate.
///
/// See https://github.com/zkcrypto/pairing/blob/master/src/bls12_381/README.md#serialization
pub fn serialize_g2(g2: &ECP2) -> [u8; G2_BYTES] {
// Check point at inifinity
if g2.is_infinity() {
let mut result = [0; G2_BYTES];
result[0] += COMPRESION_FLAG + INFINITY_FLAG;
return result;
}
// Convert x-coordinate to bytes
// Note: Zcash uses (x_im, x_re)
let mut result = [0u8; G2_BYTES];
let x = g2.getx();
x.geta().tobytes(&mut result[MODBYTES..(MODBYTES * 2)]);
x.getb().tobytes(&mut result[0..MODBYTES]);
// Check y value
let mut y = g2.gety();
let mut y_neg = y.clone();
y_neg.neg();
// Set flags
if zcash_cmp_fp2(&mut y, &mut y_neg) > 0 {
result[0] += Y_FLAG;
}
result[0] += COMPRESION_FLAG;
result
}
/// Take a G2 point (x, y) and convert it to a 192 byte array as (x, y).
///
/// See https://github.com/zkcrypto/pairing/blob/master/src/bls12_381/README.md#serialization
pub fn serialize_uncompressed_g2(g2: &ECP2) -> [u8; G2_BYTES * 2] {
let mut result = [0; G2_BYTES * 2];
// Check point at inifinity
if g2.is_infinity() {
result[0] += INFINITY_FLAG;
return result;
}
// Convert to bytes
// Note: Zcash uses (x_im, x_re), (y_im, y_re)
let x = g2.getx();
x.getb().tobytes(&mut result[0..MODBYTES]);
x.geta().tobytes(&mut result[MODBYTES..(MODBYTES * 2)]);
let x = g2.gety();
x.getb()
.tobytes(&mut result[(MODBYTES * 2)..(MODBYTES * 3)]);
x.geta().tobytes(&mut result[(MODBYTES * 3)..]);
result
}
/// Take a 96 or 192 byte array and convert to G2 point (x, y)
///
/// See https://github.com/zkcrypto/pairing/blob/master/src/bls12_381/README.md#serialization
pub fn deserialize_g2(g2_bytes: &[u8]) -> Result<ECP2, AmclError> {
if g2_bytes.len() == 0 {
return Err(AmclError::InvalidG2Size);
}
if g2_bytes[0] & COMPRESION_FLAG == 0 {
deserialize_uncompressed_g2(g2_bytes)
} else {
deserialize_compressed_g2(g2_bytes)
}
}
// Decompress a G2 point from x-coordinate
fn deserialize_compressed_g2(g2_bytes: &[u8]) -> Result<ECP2, AmclError> {
if g2_bytes.len() != G2_BYTES {
return Err(AmclError::InvalidG2Size);
}
// Check infinity flag
if g2_bytes[0] & INFINITY_FLAG != 0 {
// Trailing bits should all be 0.
if g2_bytes[0] & 0b_0011_1111 != 0 {
return Err(AmclError::InvalidPoint);
}
for item in g2_bytes.iter().skip(1) {
if *item != 0 {
return Err(AmclError::InvalidPoint);
}
}
return Ok(ECP2::new()); // infinity
}
let y_flag: bool = (g2_bytes[0] & Y_FLAG) > 0;
// Zero flags
let mut g2_bytes = g2_bytes.to_owned();
g2_bytes[0] = g2_bytes[0] & 0b_0001_1111;
// Convert from array to FP2
let x_imaginary = Big::frombytes(&g2_bytes[0..MODBYTES]);
let x_real = Big::frombytes(&g2_bytes[MODBYTES..]);
// Require elements less than field modulus
let m = Big::new_ints(&MODULUS);
if x_imaginary >= m || x_real >= m {
return Err(AmclError::InvalidPoint);
}
let x = FP2::new_bigs(x_real, x_imaginary);
// Convert to G2 from x-coordinate
let point = ECP2::new_fp2(&x);
if point.is_infinity() {
return Err(AmclError::InvalidPoint);
}
// Confirm y value
let mut point_neg = point.clone();
point_neg.neg();
if (zcash_cmp_fp2(&mut point.gety(), &mut point_neg.gety()) > 0) != y_flag {
Ok(point_neg)
} else {
Ok(point)
}
}
// Decompress a G2 point from (x, y)
fn deserialize_uncompressed_g2(g2_bytes: &[u8]) -> Result<ECP2, AmclError> {
if g2_bytes.len() != G2_BYTES * 2 {
return Err(AmclError::InvalidG2Size);
}
// Check infinity flag
if g2_bytes[0] & INFINITY_FLAG != 0 {
// Trailing bits should all be 0.
if g2_bytes[0] & 0b_0011_1111 != 0 {
return Err(AmclError::InvalidPoint);
}
for item in g2_bytes.iter().skip(1) {
if *item != 0 {
return Err(AmclError::InvalidPoint);
}
}
return Ok(ECP2::new()); // infinity
}
if (g2_bytes[0] & Y_FLAG) > 0 {
return Err(AmclError::InvalidYFlag);
}
// Zero flags
let mut g2_bytes = g2_bytes.to_owned();
g2_bytes[0] = g2_bytes[0] & 0b_0001_1111;
// Convert from array to FP2
let x_imaginary = Big::frombytes(&g2_bytes[..MODBYTES]);
let x_real = Big::frombytes(&g2_bytes[MODBYTES..(MODBYTES * 2)]);
let y_imaginary = Big::frombytes(&g2_bytes[(MODBYTES * 2)..(MODBYTES * 3)]);
let y_real = Big::frombytes(&g2_bytes[(MODBYTES * 3)..]);
// Require elements less than field modulus
let m = Big::new_ints(&MODULUS);
if x_imaginary >= m || x_real >= m || y_imaginary >= m || y_real >= m {
return Err(AmclError::InvalidPoint);
}
let x = FP2::new_bigs(x_real, x_imaginary);
let y = FP2::new_bigs(y_real, y_imaginary);
// Convert to G2 from x-coordinate
let point = ECP2::new_fp2s(x, y);
if point.is_infinity() {
return Err(AmclError::InvalidPoint);
}
Ok(point)
}
/*************************************************************************************************
* Core BLS Functions when signatures are on G1
*
* https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2
*************************************************************************************************/
/// Generate key pair - (secret key, public key)
pub(crate) fn key_pair_generate_g1(rng: &mut RAND) -> ([u8; SECRET_KEY_BYTES], [u8; G2_BYTES]) {
// Fill random bytes
let mut ikm = [0u8; SECRET_KEY_BYTES];
for byte in ikm.iter_mut() {
*byte = rng.getbyte();
}
// Generate key pair
let secret_key = key_generate(&ikm, &[]);
let public_key =
secret_key_to_public_key_g1(&secret_key).expect("Valid secret key was generated");
(secret_key, public_key)
}
/// Secret Key To Public Key
///
/// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.4
pub(crate) fn secret_key_to_public_key_g1(secret_key: &[u8]) -> Result<[u8; G2_BYTES], AmclError> {
let secret_key = secret_key_from_bytes(secret_key)?;
let g = ECP2::generator();
let public_key = pair::g2mul(&g, &secret_key);
Ok(serialize_g2(&public_key))
}
// CoreSign
//
// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.7
pub(crate) fn core_sign_g1(
secret_key: &[u8],
msg: &[u8],
dst: &[u8],
) -> Result<[u8; G1_BYTES], AmclError> {
let secret_key = secret_key_from_bytes(secret_key)?;
let hash = hash_to_curve_g1(msg, dst);
let signature = pair::g1mul(&hash, &secret_key);
Ok(serialize_g1(&signature))
}
// CoreVerify
//
// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.7
pub(crate) fn core_verify_g1(public_key: &[u8], msg: &[u8], signature: &[u8], dst: &[u8]) -> bool {
let public_key = deserialize_g2(public_key);
let signature = deserialize_g1(signature);
if public_key.is_err() || signature.is_err() {
return false;
}
let public_key = public_key.unwrap();
let signature = signature.unwrap();
// Subgroup checks for signature and public key
if !subgroup_check_g1(&signature) || !subgroup_check_g2(&public_key) {
return false;
}
// Hash msg and negate generator for pairing
let hash = hash_to_curve_g1(msg, dst);
let mut g = ECP2::generator();
g.neg();
// Pair e(H(msg), pk) * e(signature, -g)
let mut r = pair::initmp();
pair::another(&mut r, &g, &signature);
pair::another(&mut r, &public_key, &hash);
let mut v = pair::miller(&r);
v = pair::fexp(&v);
// True if pairing output is 1
v.isunity()
}
/// Aggregate
///
/// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.8
pub(crate) fn aggregate_g1(points: &[&[u8]]) -> Result<[u8; G1_BYTES], AmclError> {
if points.len() == 0 {
return Err(AmclError::AggregateEmptyPoints);
}
let mut aggregate = deserialize_g1(&points[0])?;
for point in points.iter().skip(1) {
aggregate.add(&deserialize_g1(&point)?);
}
Ok(serialize_g1(&aggregate))
}
// CoreAggregateVerify
//
// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.9
pub(crate) fn core_aggregate_verify_g1(
public_keys: &[&[u8]],
msgs: &[&[u8]],
signature: &[u8],
dst: &[u8],
) -> bool {
// Preconditions
if public_keys.len() == 0 || public_keys.len() != msgs.len() {
return false;
}
let signature = deserialize_g1(signature);
if signature.is_err() {
return false;
}
let signature = signature.unwrap();
// Subgroup checks for signature
if !subgroup_check_g1(&signature) {
return false;
}
// Pair e(signature, -g)
let mut g = ECP2::generator();
g.neg();
let mut r = pair::initmp();
pair::another(&mut r, &g, &signature);
for (i, public_key) in public_keys.iter().enumerate() {
let public_key = deserialize_g2(public_key);
if public_key.is_err() {
return false;
}
let public_key = public_key.unwrap();
if !subgroup_check_g2(&public_key) {
return false;
}
// Pair *= e(pk[i], H(msgs[i]))
let hash = hash_to_curve_g1(msgs[i], dst);
pair::another(&mut r, &public_key, &hash);
}
// True if pairing output is 1
let mut v = pair::miller(&r);
v = pair::fexp(&v);
v.isunity()
}
/*************************************************************************************************
* Core BLS Functions when signatures are on G2
*
* https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2
*************************************************************************************************/
/// Generate key pair - (secret key, public key)
pub(crate) fn key_pair_generate_g2(rng: &mut RAND) -> ([u8; SECRET_KEY_BYTES], [u8; G1_BYTES]) {
// Fill random bytes
let mut ikm = [0u8; SECRET_KEY_BYTES];
for byte in ikm.iter_mut() {
*byte = rng.getbyte();
}
// Generate key pair
let secret_key = key_generate(&ikm, &[]);
let public_key =
secret_key_to_public_key_g2(&secret_key).expect("Valid secret key was generated");
(secret_key, public_key)
}
/// Secret Key To Public Key
///
/// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.4
pub(crate) fn secret_key_to_public_key_g2(secret_key: &[u8]) -> Result<[u8; G1_BYTES], AmclError> {
let secret_key = secret_key_from_bytes(secret_key)?;
let g = ECP::generator();
let public_key = pair::g1mul(&g, &secret_key);
// Convert to bytes
Ok(serialize_g1(&public_key))
}
// CoreSign
//
// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.7
pub(crate) fn core_sign_g2(
secret_key: &[u8],
msg: &[u8],
dst: &[u8],
) -> Result<[u8; G2_BYTES], AmclError> {
let secret_key = secret_key_from_bytes(secret_key)?;
let hash = hash_to_curve_g2(msg, dst);
let signature = pair::g2mul(&hash, &secret_key);
Ok(serialize_g2(&signature))
}
// CoreVerify
//
// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.7
pub(crate) fn core_verify_g2(public_key: &[u8], msg: &[u8], signature: &[u8], dst: &[u8]) -> bool {
let public_key = deserialize_g1(public_key);
let signature = deserialize_g2(signature);
if public_key.is_err() || signature.is_err() {
return false;
}
let public_key = public_key.unwrap();
let signature = signature.unwrap();
// Subgroup checks for signature and public key
if !subgroup_check_g1(&public_key) || !subgroup_check_g2(&signature) {
return false;
}
// Hash msg and negate generator for pairing
let hash = hash_to_curve_g2(msg, dst);
let mut g = ECP::generator();
g.neg();
// Pair e(H(msg), pk) * e(signature, -g)
let mut r = pair::initmp();
pair::another(&mut r, &signature, &g);
pair::another(&mut r, &hash, &public_key);
let mut v = pair::miller(&r);
v = pair::fexp(&v);
// True if pairing output is 1
v.isunity()
}
/// Aggregate
///
/// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.8
pub(crate) fn aggregate_g2(points: &[&[u8]]) -> Result<[u8; G2_BYTES], AmclError> {
if points.len() == 0 {
return Err(AmclError::AggregateEmptyPoints);
}
let mut aggregate = deserialize_g2(&points[0])?;
for point in points.iter().skip(1) {
aggregate.add(&deserialize_g2(&point)?);
}
Ok(serialize_g2(&aggregate))
}
// CoreAggregateVerify
//
// https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-02#section-2.9
pub(crate) fn core_aggregate_verify_g2(
public_keys: &[&[u8]],
msgs: &[&[u8]],
signature: &[u8],
dst: &[u8],
) -> bool {
let signature = deserialize_g2(signature);
if signature.is_err() {
return false;
}
let signature = signature.unwrap();
// Preconditions
if public_keys.len() == 0 || public_keys.len() != msgs.len() {
return false;
}
// Subgroup checks for signature
if !subgroup_check_g2(&signature) {
return false;
}
// Pair e(signature, -g)
let mut g = ECP::generator();
g.neg();
let mut r = pair::initmp();
pair::another(&mut r, &signature, &g);
for (i, public_key) in public_keys.iter().enumerate() {
let public_key = deserialize_g1(public_key);
if public_key.is_err() {
return false;
}
let public_key = public_key.unwrap();
// Subgroup check for public key
if !subgroup_check_g1(&public_key) {
return false;
}
// Pair *= e(pk[i], H(msgs[i]))
let hash = hash_to_curve_g2(msgs[i], dst);
pair::another(&mut r, &hash, &public_key);
}
// True if pairing output is 1
let mut v = pair::miller(&r);
v = pair::fexp(&v);
v.isunity()
}
/*************************************************************************************************
* Functions for hashing to curve when signatures are on G1
*************************************************************************************************/
/// Hash to Curve
///
/// Takes a message as input and converts it to a Curve Point
/// https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-07#section-3
pub fn hash_to_curve_g1(msg: &[u8], dst: &[u8]) -> ECP {
let u =
hash_to_field_fp(msg, 2, dst).expect("hash to field should not fail for given parameters");
let mut q0 = map_to_curve_g1(u[0].clone());
let q1 = map_to_curve_g1(u[1].clone());
q0.add(&q1);
let p = q0.mul(&H_EFF_G1);
p
}
// Simplified SWU for Pairing-Friendly Curves
//
// Take a field point and map it to a Curve Point.
// SSWU - https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-07#section-6.6.2
// ISO11 - https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-07#appendix-C.2
fn map_to_curve_g1(u: FP) -> ECP {
let (x, y) = simplified_swu_fp(u);
iso11_to_ecp(&x, &y)
}
/*************************************************************************************************
* Functions for hashing to curve when signatures are on G2
*************************************************************************************************/
/// Hash to Curve
///
/// Takes a message as input and converts it to a Curve Point
/// https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-07#section-3
pub fn hash_to_curve_g2(msg: &[u8], dst: &[u8]) -> ECP2 {
let u =
hash_to_field_fp2(msg, 2, dst).expect("hash to field should not fail for given parameters");
let mut q0 = map_to_curve_g2(u[0].clone());
let q1 = map_to_curve_g2(u[1].clone());
q0.add(&q1);
q0.clear_cofactor();
q0
}
// Simplified SWU for Pairing-Friendly Curves
//
// Take a field point and map it to a Curve Point.
// SSWU - https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-07#section-6.6.2
// ISO3 - https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-07#appendix-C.3
fn map_to_curve_g2(u: FP2) -> ECP2 {
let (x, y) = simplified_swu_fp2(u);
iso3_to_ecp2(&x, &y)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::*;
const TEST_DST: &[u8] = b"BLS_TEST_";
#[test]
fn test_hash_to_curve_g2() {
const H2C_SUITE_G2: &str = "BLS12381G2_XMD:SHA-256_SSWU_RO_";
// Read hash to curve test vector
let reader = json_reader(H2C_SUITE_G2);
let test_vectors: Bls12381Ro = serde_json::from_reader(reader).unwrap();
// Iterate through each individual case
for case in test_vectors.vectors {
// Execute hash to curve
let u = hash_to_field_fp2(case.msg.as_bytes(), 2, test_vectors.dst.as_bytes()).unwrap();
let q0 = map_to_curve_g2(u[0].clone());
let q1 = map_to_curve_g2(u[1].clone());
let mut r = q0.clone();
r.add(&q1);
let mut p = r.clone();
p.clear_cofactor();
// Verify against hash_to_curve()
let hash_to_curve_p =
hash_to_curve_g2(case.msg.as_bytes(), test_vectors.dst.as_bytes());
assert_eq!(hash_to_curve_p, p);
// Verify hash to curve outputs
// Check u
assert_eq!(case.u.len(), u.len());
for (i, u_str) in case.u.iter().enumerate() {
// Convert case 'u[i]' to FP2
let u_str_parts: Vec<&str> = u_str.split(',').collect();
let a = Big::frombytes(&hex::decode(&u_str_parts[0].get(2..).unwrap()).unwrap());
let b = Big::frombytes(&hex::decode(&u_str_parts[1].get(2..).unwrap()).unwrap());
let expected_u_i = FP2::new_bigs(a, b);
// Verify u[i]
assert_eq!(expected_u_i, u[i]);
}
// Check Q0
let x_str_parts: Vec<&str> = case.Q0.x.split(',').collect();
let a = Big::frombytes(&hex::decode(&x_str_parts[0].get(2..).unwrap()).unwrap());
let b = Big::frombytes(&hex::decode(&x_str_parts[1].get(2..).unwrap()).unwrap());
let expected_x = FP2::new_bigs(a, b);
let y_str_parts: Vec<&str> = case.Q0.y.split(',').collect();
let a = Big::frombytes(&hex::decode(&y_str_parts[0].get(2..).unwrap()).unwrap());
let b = Big::frombytes(&hex::decode(&y_str_parts[1].get(2..).unwrap()).unwrap());
let expected_y = FP2::new_bigs(a, b);
let expected_q0 = ECP2::new_fp2s(expected_x, expected_y);
assert_eq!(expected_q0, q0);
// Check Q1
let x_str_parts: Vec<&str> = case.Q1.x.split(',').collect();
let a = Big::frombytes(&hex::decode(&x_str_parts[0].get(2..).unwrap()).unwrap());
let b = Big::frombytes(&hex::decode(&x_str_parts[1].get(2..).unwrap()).unwrap());
let expected_x = FP2::new_bigs(a, b);
let y_str_parts: Vec<&str> = case.Q1.y.split(',').collect();
let a = Big::frombytes(&hex::decode(&y_str_parts[0].get(2..).unwrap()).unwrap());
let b = Big::frombytes(&hex::decode(&y_str_parts[1].get(2..).unwrap()).unwrap());
let expected_y = FP2::new_bigs(a, b);
let expected_q1 = ECP2::new_fp2s(expected_x, expected_y);
assert_eq!(expected_q1, q1);
// Check P
let x_str_parts: Vec<&str> = case.P.x.split(',').collect();
let a = Big::frombytes(&hex::decode(&x_str_parts[0].get(2..).unwrap()).unwrap());
let b = Big::frombytes(&hex::decode(&x_str_parts[1].get(2..).unwrap()).unwrap());
let expected_x = FP2::new_bigs(a, b);
let y_str_parts: Vec<&str> = case.P.y.split(',').collect();
let a = Big::frombytes(&hex::decode(&y_str_parts[0].get(2..).unwrap()).unwrap());
let b = Big::frombytes(&hex::decode(&y_str_parts[1].get(2..).unwrap()).unwrap());
let expected_y = FP2::new_bigs(a, b);
let expected_p = ECP2::new_fp2s(expected_x, expected_y);
assert_eq!(expected_p, p);
}
}
#[test]
fn test_hash_to_curve_g1() {
const H2C_SUITE_G1: &str = "BLS12381G1_XMD:SHA-256_SSWU_RO_";
// Read hash to curve test vector
let reader = json_reader(H2C_SUITE_G1);
let test_vectors: Bls12381Ro = serde_json::from_reader(reader).unwrap();
// Iterate through each individual case
for case in test_vectors.vectors {
// Execute hash to curve
let u = hash_to_field_fp(case.msg.as_bytes(), 2, test_vectors.dst.as_bytes()).unwrap();
let q0 = map_to_curve_g1(u[0].clone());
let q1 = map_to_curve_g1(u[1].clone());
let mut r = q0.clone();
r.add(&q1);
let p = r.mul(&H_EFF_G1);
// Verify against hash_to_curve()
let hash_to_curve_p =
hash_to_curve_g1(case.msg.as_bytes(), test_vectors.dst.as_bytes());
assert_eq!(hash_to_curve_p, p);
// Verify hash to curve outputs
// Check u
assert_eq!(case.u.len(), u.len());
for (i, u_str) in case.u.iter().enumerate() {
// Convert case 'u[i]' to FP
let a = Big::frombytes(&hex::decode(&u_str.get(2..).unwrap()).unwrap());
let expected_u_i = FP::new_big(a);
// Verify u[i]
assert_eq!(expected_u_i, u[i]);
}
// Check Q0
let a = Big::frombytes(&hex::decode(&case.Q0.x.get(2..).unwrap()).unwrap());
let expected_x = FP::new_big(a);
let a = Big::frombytes(&hex::decode(&case.Q0.y.get(2..).unwrap()).unwrap());
let expected_y = FP::new_big(a);
let expected_q0 = ECP::new_fps(expected_x, expected_y);
assert_eq!(expected_q0, q0);
// Check Q1
let a = Big::frombytes(&hex::decode(&case.Q1.x.get(2..).unwrap()).unwrap());
let expected_x = FP::new_big(a);
let a = Big::frombytes(&hex::decode(&case.Q1.y.get(2..).unwrap()).unwrap());
let expected_y = FP::new_big(a);
let expected_q1 = ECP::new_fps(expected_x, expected_y);
assert_eq!(expected_q1, q1);
// Check P
let a = Big::frombytes(&hex::decode(&case.P.x.get(2..).unwrap()).unwrap());
let expected_x = FP::new_big(a);
let a = Big::frombytes(&hex::decode(&case.P.y.get(2..).unwrap()).unwrap());
let expected_y = FP::new_big(a);
let expected_p = ECP::new_fps(expected_x, expected_y);
assert_eq!(expected_p, p);
}
}
#[test]
fn test_secret_key_generation() {
let ikm = [1u8; 32];
let sk = key_generate(&ikm, &[]);