-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlogarithm-finding.sage
1491 lines (1095 loc) · 47.1 KB
/
logarithm-finding.sage
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
# ------------------------------------------------------------------------------
# In [EG23p], an extension of Regev's factoring quantum algorithm [Regev23] to
# the discrete logarithm problem was introduced. This Sage script (and the
# associated supporting scripts) implements a simulator for the quantum
# algorithm in [EG23p], alongside the classical post-processing algorithm from
# [EG23p] that recovers the logarithm from simulated samples.
#
# [Regev23] Regev, O.: "An Efficient Quantum Factoring Algorithm".
# ArXiv 2308.06572v2 (2023).
#
# [EG23p] Ekerå, M. and Gärtner, J.: "Extending Regev’s factoring algorithm
# to compute discrete logarithms".
# ArXiv 2311.05545v2 (2023–2024).
from datetime import datetime
import platform
from dependencies.timer import Timer
load("common.sage")
load("simulator.sage")
load("problem-instances.sage")
load("parameter-search.sage")
load("uids.sage")
def has_maximal_order(g, p):
"""
@brief Checks if g has maximal multiplicative order p - 1 mod p, for p a
prime such that p - 1 is B-smooth for B some small bound.
@param g The generator g of order r.
@param p The prime p.
@return True if g has maximal multiplicative order mod p, False otherwise.
"""
F = GF(p, proof=False)
g = F(g)
for [q, _] in factor(p - 1):
if g^((p - 1) / q) == 1:
return False
return True
def find_smooth_logarithm_mod_p(g, x, p):
"""
@brief Finds the discrete logarithm e such that x = g^e mod p, for p a
prime such that p - 1 is B-smooth for B some small bound.
The logarithm returned is on [0, r) for r the order of g.
@param g The generator g of order r.
@param x The element x = g^e mod p.
@param p The prime p.
@return The discrete logarithm e on [0, r) for r the order of g.
"""
F = GF(p, proof=False)
g = F(g)
x = F(x)
r = find_smooth_order_mod_p(g, p)
logs = []
for [q, _] in factor(p - 1):
gq = g^((p - 1) / q)
xq = x^((p - 1) / q)
eq = discrete_log(xq, gq)
# Sanity check.
if gq^eq != xq:
raise Exception("Error: Internal error (1).")
logs.append([eq, q])
# Use the Chinese remainder theorem to compose the solutions.
e = CRT([d for [d, _] in logs], [q for [_, q] in logs])
# Sanity check.
if g^e != x:
raise Exception("Error: Internal error (2).")
return e % r
def build_logarithm_finding_element_vector(d, u):
"""
@brief Builds the element vector (g_1, .., g_{d-k}, u_1, .., u_k), where
g_1, .., g_{d-k} are the first d - k primes that are distinct from
u_1, .., u_k over the integers.
@param d The dimension d of the elements vector to build.
@param u A list [u_1, .., u_k] of the element u_1, .., u_k.
@return The elements vector b = (g_1, .., g_{d-k}, u_1, .., u_k) built.
"""
k = len(u)
# Sanity check.
if k > d:
raise Exception("Error: The vector u has more than d elements.")
gis = []
gi = 2
while len(gis) < d - k:
if gi not in u:
gis.append(gi)
gi = gi.next_prime()
return gis + u
def generate_basis_for_logarithm_finding(
p,
u,
d=None,
*,
threads=DEFAULT_THREADS,
verbose=False):
"""
@brief Generates a basis for the d-dimensional lattice L_{u_1, .., u_k}
used for computing orders and discrete logarithms mod p, when
given the dimension d, the prime p and the k elements u_1, .., u_k.
The prime p must be such that p - 1 is B-smooth for B some small bound.
The vectors (z_1, .., z_d) in L_{u_1, .., u_k} are such that
g_1^{z_1} * ... * g_{d-k}^{z_{d-k}} * \
u_1^{z_{d-k+1}} * ... * u_k^{z_d} = 1 (mod p),
where g_1, .., g_{d-k} are the first d - k first primes distinct from the
elements in u = [u_1, .., u_k].
@param p The prime p.
@param u A list [u_1, .., u_k] of the elements u_1, .., u_k.
@param d The dimension d of the lattice L_{u_1, .., u_k}. Set to
ceil(sqrt(n)), for n the bit length of p, if omitted.
@param threads The number of threads to use when sampling.
@param verbose A flag that may be set to True to print verbose status
messages, or to False not to print such messages.
@return A basis for the lattice L_{u_1, .., u_k} used for computing
discrete logarithms and orders mod p.
"""
if d == None:
n = p.nbits()
d = ceil(sqrt(n))
b = build_logarithm_finding_element_vector(d, u)
return generate_basis_for_L(p, [p], b, threads=threads, verbose=verbose)
def solve_samples_for_logarithm(
samples,
g,
x,
p,
R,
*,
block_size=DEFAULT_BLOCK_SIZE,
profile_file=None,
verbose=False):
"""
@brief Solves a list of samples for the discrete logarithm e such that
x = g^e mod p for g, x and p as passed to this function when not
pre-computing the logarithms of the small generators and instead
including both g and x in the lattice.
This function also computes the order r of g from the sampled vectors.
The prime p must be B-smooth for B some small bound.
@param samples The list of samples to solve for the discrete logarithm.
@param R The parameter R specifying the standard deviation of the noise.
@param g The generator g of order r.
@param x The element x = g^e mod p.
@param p The prime.
@param block_size The blocksize for lattice reduction used during
post-processing. For the default value of 2, LLL is
used. For larger block-sizes, BKZ is used instead.
@param profile_file The path to a file in which to save the profile of the
Gram–Schmidt norms of the post-processing matrix. If
omitted no profile is saved.
@param verbose A flag that may be set to True to print verbose status
messages, or to False not to print such messages.
@return The candidate for the discrete logarithm e on [0, r), or None if
the classical post-processing failed to recover such a candidate.
"""
# Setup and start a timer.
timer = Timer().start()
# Print status.
if verbose:
print("Post-processing the sampled vectors to find the logarithm...")
print(" Building the post-processing matrix...")
# Extract the dimension.
d = samples[0].dimensions()[1]
for i in range(1, len(samples)):
if d != samples[i].dimensions()[1]:
raise Exception("Error: The samples differ in their dimensions.")
# Pick S as described in [Regev23]: In Corollary 4.5 of [Regev23], S = δ^-1,
# and δ = sqrt(d) / (sqrt(2) R) on p. 7 of [Regev23].
S = ceil(sqrt(2 / d) * R)
M = build_M_matrix(samples, S)
# Run a lattice basis reduction algorithm on the post-processing matrix, and
# then extract the relevant submatrix.
if block_size != 2:
# Use BKZ with the prescribed block size to reduce the lattice basis.
if verbose:
print(" Running BKZ on the post-processing matrix...")
denominator = M.denominator()
X = (M * denominator).change_ring(ZZ).BKZ(
block_size=block_size, algorithm="fpLLL", fp="rr", precision=128
) / denominator
else:
# Use LLL to reduce the lattice basis.
if verbose:
print(" Running LLL on the post-processing matrix...")
X = M.LLL()
if X.row_space() != M.row_space():
raise Exception("Error: Failed to run BKZ/LLL.")
if profile_file != None:
if verbose:
print(" Saving the profile after reduction...")
XR = X.change_ring(RDF)
(XRgs, _) = XR.gram_schmidt()
with open(profile_file, "w") as f:
for i in range(XR.dimensions()[0]):
f.write(f"{log(abs(XR[i] * XRgs[i]), 2).n()}\n")
LB = X[:, :d]
# Build the elements vector b.
b = build_logarithm_finding_element_vector(d, u = [x, g])
Lxg = None
for row in LB:
if row == 0:
break
if not is_in_lattice(row, p, b):
continue
if Lxg == None:
Lxg = matrix(ZZ, row)
S = Lxg.row_space()
else:
if row not in S:
Lxg = Lxg.stack(row)
# Sanity check.
if None == Lxg:
raise Exception("Error: Failed to find d linearly independent vectors.")
# Use LLL to remove any linear dependence in the generating set.
Lxg = Lxg.LLL()[-d:, :]
if verbose:
print(" Found", Lxg.rank(), "/", d, "linearly independent vectors...")
# Sanity checks.
if Lxg.rank() != d:
raise Exception("Error: Failed to find d linearly independent vectors.")
# Solve for v_r = [0, .., 0, r] and v_e = [0, .., 0, a, b].
S = matrix(ZZ, Lxg)
Sp = S.hermite_form()
v_r = Sp[d - 1, :]
r = v_r[0, d - 1]
v_d = Sp[d - 2, :]
a = v_d[0, d - 2]
b = v_d[0, d - 1]
# N.B.: There is no point in adding Sp[d - 1, :] to v, since the last
# component of Sp[d - 1, :] must be an integer multiple of r.
tau = gcd(a, r)
if tau == 1:
R = IntegerModRing(r)
e = (R(-b) / R(a)).lift()
else:
return None
if verbose:
print("")
print(" Found e =", e)
print(" Found r =", r)
print("")
print(" Time required to post-process:", timer)
# Return the logarithm.
return e
def solve_samples_for_logarithm_with_precomputation(
samples,
g,
x,
p,
R,
*,
block_size=DEFAULT_BLOCK_SIZE,
profile_file=None,
verbose=False):
"""
@brief Solves a list of samples for the discrete logarithm e such that
x = g^e mod p for g, x and p as passed to this function when
pre-computing the logarithms of the small generators.
The prime p must be such that p - 1 is B-smooth for B some small bound.
This function assumes that the order r of g mod p is known; it uses the
fact that p - 1 is smooth to compute the order. Similarly, this function
assumes that the logarithms e_i such that g = g_i^e_i mod p are known for
all i in [0, d); it uses the fact p - 1 is smooth to compute the logarithms.
@param samples The list of samples to solve for the discrete logarithm.
@param g The generator g of order r.
@param x The element x = g^e mod p.
@param p The prime p.
@param R The parameter R specifying the standard deviation of the noise.
@param block_size The blocksize for lattice reduction used during
post-processing. For the default value of 2, LLL is
used. For larger block-sizes, BKZ is used instead.
@param profile_file The path to a file in which to save the profile of the
Gram–Schmidt norms of the post-processing matrix. If
omitted no profile is saved.
@param verbose A flag that may be set to True to print verbose status
messages, or to False not to print such messages.
@return The candidate for the discrete logarithm e on [0, r), or None if
the classical post-processing failed to recover such a candidate.
"""
# Setup and start a timer.
timer = Timer().start()
# Print status.
if verbose:
print("Post-processing the sampled vectors to find the logarithm...")
print(" Building the post-processing matrix...")
# Extract the dimension.
d = samples[0].dimensions()[1]
for i in range(1, len(samples)):
if d != samples[i].dimensions()[1]:
raise Exception("Error: The samples differ in their dimensions.")
# Pick S as described in [Regev23]: In Corollary 4.5 of [Regev23], S = δ^-1,
# and δ = sqrt(d) / (sqrt(2) R) on p. 7 of [Regev23].
S = ceil(sqrt(2 / d) * R)
M = build_M_matrix(samples, S)
# Run a lattice basis reduction algorithm on the post-processing matrix, and
# then extract the relevant submatrix.
if block_size != 2:
# Use BKZ with the prescribed block size to reduce the lattice basis.
if verbose:
print(" Running BKZ on the post-processing matrix...")
denominator = M.denominator()
X = (M * denominator).change_ring(ZZ).BKZ(
block_size=block_size, algorithm="fpLLL", fp="rr", precision=128
) / denominator
else:
# Use LLL to reduce the lattice basis.
if verbose:
print(" Running LLL on the post-processing matrix...")
X = M.LLL()
if X.row_space() != M.row_space():
raise Exception("Error: Failed to run BKZ/LLL.")
if profile_file != None:
if verbose:
print(" Saving the profile after reduction...")
XR = X.change_ring(RDF)
(XRgs, _) = XR.gram_schmidt()
with open(profile_file, "w") as f:
for i in range(XR.dimensions()[0]):
f.write(f"{log(abs(XR[i] * XRgs[i]), 2).n()}\n")
LB = X[:d, :d]
# Build the elements vector b.
b = build_logarithm_finding_element_vector(d, [x])
# Assume the order r of g mod p to be known.
r = find_smooth_order_mod_p(g, p)
# Pre-compute the logarithms e_i such that g^e_i = b_i mod p.
e = [find_smooth_logarithm_mod_p(g, bi, p) for bi in b[ : d - 1]]
# Setup the ring of integers mod p.
R = IntegerModRing(p)
if verbose:
print("")
print(" Processing the relations found...")
e_found = None
for v in LB:
if not is_in_lattice(v, p, b):
continue
# We have: g_1^v_1 * ... * g_{d-1}^v_{d-1} * x^v_d = 1 = g^0.
#
# => v_1 e_1 + ... + v_{d-1} e_{d-1} + v_d e_d = 0 (mod r)
# => e_d = -(v_1 e_1 + ... + v_{d-1} e_{d-1}) / v_d (mod r)
if gcd(r, v[d - 1]) != 1:
continue
Rr = IntegerModRing(r)
sum_vi_ei = Rr(-sum([v[i] * e[i] for i in range(d - 1)]))
e_found = (sum_vi_ei / Rr(v[d - 1])).lift()
if verbose:
print(" Found e =", e_found)
break
if verbose:
print("")
print(" Time required to post-process:", timer)
# Return the logarithm.
return e_found
def test_logarithm_finding_in_safe_prime_group(
l=2048,
*,
B=DEFAULT_BOUND_B,
C=DEFAULT_CONSTANT_C,
dp=1,
mp=None,
failure_rate=0,
block_size=DEFAULT_BLOCK_SIZE,
threads=DEFAULT_THREADS,
verbose=True):
"""
@brief A convenience function for testing the simulator for the quantum
algorithm in [EG23p], and the associated classical post-processing,
with respect to computing discrete logarithms in simulated
safe-prime groups.
[EG23p] Ekerå, M. and Gärtner, J.: "Extending Regev's factoring algorithm
to compute discrete logarithms".
ArXiv 2311.05545v2 (2023).
This function first picks domain parameters for a simulated safe-prime
group. Specifically, this function first samples an l-bit prime p such that
p - 1 is B-smooth for some small bound B (to enable efficient simulation).
It then picks the smallest generator g that is of order r = (p - 1) / 2.
This function also sets up a problem instance x = g^e mod p by sampling e
uniformly at random from [0, r) and computing x.
It then sets up the simulator, and uses the simulator to sample m vectors
representative of vectors that the quantum algorithm would output for the
problem instance (g, x, p) according to the analysis in [EG23p].
Finally, it solves the vectors sampled for the discrete logarithm e by
using the lattice-based post-processing from [EG23p].
@param l The bit length of the prime p.
@param B The bound B on the smoothness of p - 1.
@param C The constant C that specifies the control register lengths.
@param dp A scaling factor d' such that d = ceil(d' * sqrt(n)).
@param mp A scaling factor m' such that m = ceil(m' * sqrt(n)). If
omitted, m = ceil(sqrt(n)) + 4 as in Regev's original analysis.
@param failure_rate The failure rate on [0, 1). May be set to a value
greater than zero to simulate error-correction
failures resulting in bad vectors being output.
@param block_size The blocksize for lattice reduction used during
post-processing. For the default value of 2, LLL is
used. For larger block-sizes, BKZ is used instead.
@param threads The number of threads to use when sampling.
@param verbose A flag that may be set to True to print verbose status
messages, or to False not to print such messages.
@return Return True if the discrete logarithm was successfully recovered,
returns False otherwise.
"""
# Setup the problem instance.
if verbose:
print("** Setting up the problem instance...")
print("")
# Sample the domain parameters [g, p].
[g, p] = sample_domain_parameters_safe_prime(l, B, verbose=verbose)
# Sample [x, e] such that x = g^e where e is uniformly selected from [0, r)
# for r the order of g.
[x, e] = sample_x(g, p)
if verbose:
print("")
print(" Sampled e =", e)
print(" Computed x = g^e mod p =", x)
# Setup the simulator.
if verbose:
print("")
print("** Setting up the simulator...")
print("")
n = p.nbits()
d = ceil(dp * sqrt(n))
if mp == None:
m = ceil(sqrt(n)) + 4
else:
m = ceil(mp * sqrt(n))
B = generate_basis_for_logarithm_finding(
p, u=[x, g], d=d, threads=threads, verbose=verbose
)
if verbose:
print("")
simulator = Simulator(B, threads=threads, verbose=verbose)
if verbose:
print("")
print("** Sampling vectors...")
print("")
R = get_regev_R(C, n)
samples = simulator.sample_vectors_with_failure_rate(
R, m=m, failure_rate=failure_rate, verbose=verbose
)
if verbose:
print("")
print("** Solving for the logarithm...")
print("")
e_found = solve_samples_for_logarithm(
samples, g, x, p, R, block_size=block_size, verbose=verbose
)
return e_found == e
def test_logarithm_finding_in_schnorr_group(
l=2048,
k=224,
*,
B=DEFAULT_BOUND_B,
C=DEFAULT_CONSTANT_C,
dp=1,
mp=None,
failure_rate=0,
block_size=DEFAULT_BLOCK_SIZE,
threads=DEFAULT_THREADS,
verbose=True):
"""
@brief A convenience function for testing the simulator for the quantum
algorithm in [EG23p], and the associated classical post-processing,
with respect to computing discrete logarithms in simulated Schnorr
groups.
[EG23p] Ekerå, M. and Gärtner, J.: "Extending Regev's factoring algorithm
to compute discrete logarithms".
ArXiv 2311.05545v2 (2023).
This function first picks domain parameters for a simulated Schnorr group.
Specifically, this function first samples an l-bit prime p such that p - 1
is B-smooth for some small bound B (to enable efficient simulation), and
such that p - 1 = 2 * u * r where r is of length approximately k bits. It
then picks a generator g that is of order r.
This function also sets up a problem instance x = g^e mod p by sampling e
uniformly at random from [0, r) and computing x.
It then sets up the simulator, and uses the simulator to sample m vectors
representative of vectors that the quantum algorithm would output for the
problem instance (g, x, p) according to the analysis in [EG23p].
Finally, it solves the vectors sampled for the discrete logarithm e by
using the lattice-based post-processing from [EG23p]. This post-processing
also yields the order r of g, so r need not be assumed known.
@param l The bit length of the prime p.
@param k The approximate bit length of the order r of g.
@param B The bound B on the smoothness of p - 1.
@param C The constant C that specifies the control register lengths.
@param dp A scaling factor d' such that d = ceil(d' * sqrt(n)).
@param mp A scaling factor m' such that m = ceil(m' * sqrt(n)). If
omitted, m = ceil(sqrt(n)) + 4 as in Regev's original analysis.
@param failure_rate The failure rate on [0, 1). May be set to a value
greater than zero to simulate error-correction
failures resulting in bad vectors being output.
@param block_size The blocksize for lattice reduction used during
post-processing. For the default value of 2, LLL is
used. For larger block-sizes, BKZ is used instead.
@param threads The number of threads to use when sampling.
@param verbose A flag that may be set to True to print verbose status
messages, or to False not to print such messages.
@return Return True if the discrete logarithm was successfully recovered,
returns False otherwise.
"""
# Setup the problem instance.
if verbose:
print("** Setting up the problem instance...")
print("")
# Sample the domain parameters [g, p].
[g, p] = sample_domain_parameters_schnorr(l, k, B, verbose=verbose)
# Sample [x, e] such that x = g^e where e is uniformly selected from [0, r)
# for r the order of g.
[x, e] = sample_x(g, p)
if verbose:
print("")
print(" Sampled e =", e)
print(" Computed x = g^e mod p =", x)
# 1. Solve for e = log_{g}(x).
# Setup the simulator.
if verbose:
print("")
print("** Setting up the simulator...")
print("")
n = p.nbits()
d = ceil(dp * sqrt(n))
if mp == None:
m = ceil(sqrt(n)) + 4
else:
m = ceil(mp * sqrt(n))
B = generate_basis_for_logarithm_finding(
p, u=[x, g], d=d, threads=threads, verbose=verbose
)
if verbose:
print("")
simulator = Simulator(B, threads=threads, verbose=verbose)
if verbose:
print("")
print("** Sampling vectors...")
print("")
R = get_regev_R(C, n)
samples = simulator.sample_vectors_with_failure_rate(
R, m=m, failure_rate=failure_rate, verbose=verbose
)
if verbose:
print("")
print("** Solving for the logarithm...")
print("")
e_found = solve_samples_for_logarithm(
samples, g, x, p, R, block_size=block_size, verbose=verbose
)
return e_found == e
def test_logarithm_finding_in_safe_prime_group_with_precomputation(
l=2048,
*,
B=DEFAULT_BOUND_B,
C=DEFAULT_CONSTANT_C,
dp=1,
mp=None,
failure_rate=0,
block_size=DEFAULT_BLOCK_SIZE,
threads=DEFAULT_THREADS,
verbose=True):
"""
@brief A convenience function for testing the simulator for the quantum
algorithm in [EG23p], and the associated classical post-processing,
with respect to computing discrete logarithms in simulated
safe-prime groups with pre-computation.
[EG23p] Ekerå, M. and Gärtner, J.: "Extending Regev's factoring algorithm
to compute discrete logarithms".
ArXiv 2311.05545v2 (2023).
This function first picks domain parameters for a simulated safe-prime
group. Specifically, this function first samples an l-bit prime p such that
p - 1 is B-smooth for some small bound B (to enable efficient simulation).
It then picks a generator g that is of order r = (p - 1) / 2.
This function also sets up a problem instance x = g^e mod p by sampling e
uniformly at random from [0, r) and computing x.
It then sets up the simulator, and uses the simulator to sample vectors
representative of vectors that the quantum algorithm would output for the
problem instance (g, x, p) according to the analysis in [EG23p].
Specifically, this function sets up and uses the simulator two times:
- It first picks a generator g_max of the full group Z_p^*.
- Using the assumed knowledge of e_i such that g_i = g_max^e_i, it solves m
vectors sampled for the problem instance (g_max, g, p) for the discrete
logarithm e_g such that g = g_max^e_g using the lattice-based
post-processing from [EG23p]. This step may be pre-computed.
- Again, using the assumed knowledge of e_i such that g_i = g_max^e_i, it
solves m vectors sampled for the problem instance (g_max, x, p) for the
discrete logarithm e_x such that x = g_max^e_x using the lattice-based
post-processing from [EG23p].
Finally, using that r = (p - 1) / 2, it computes e = e_x / e_g mod r.
@param l The bit length of the prime p.
@param B The bound B on the smoothness of p - 1.
@param C The constant C that specifies the control register lengths.
@param dp A scaling factor d' such that d = ceil(d' * sqrt(n)).
@param mp A scaling factor m' such that m = ceil(m' * sqrt(n)). If
omitted, m = ceil(sqrt(n)) + 4 as in Regev's original analysis.
@param failure_rate The failure rate on [0, 1). May be set to a value
greater than zero to simulate error-correction
failures resulting in bad vectors being output.
@param block_size The blocksize for lattice reduction used during
post-processing. For the default value of 2, LLL is
used. For larger block-sizes, BKZ is used instead.
@param threads The number of threads to use when sampling.
@param verbose A flag that may be set to True to print verbose status
messages, or to False not to print such messages.
@return Return True if the discrete logarithm was successfully recovered,
returns False otherwise.
"""
# Setup the problem instance.
if verbose:
print("** Setting up the problem instance...")
print("")
# Sample the domain parameters [g, p].
[g, p] = sample_domain_parameters_safe_prime(l, B=B, verbose=verbose)
# Sample [x, e] such that x = g^e where e is uniformly selected from [0, r)
# for r the order of g.
[x, e] = sample_x(g, p)
if verbose:
print("")
print(" Sampled e =", e)
print(" Computed x = g^e mod p =", x)
# Sample a generator g_max for the full group.
g_max = 2
while not has_maximal_order(g_max, p):
g_max += 1
if verbose:
print("")
print(" Selected g_max =", g_max)
# 1. Solve for e_x = log_{g_max}(x).
# Setup the simulator.
if verbose:
print("")
print("** Setting up the simulator to compute e = log_{g_max}(x) ...")
print("")
n = p.nbits()
d = ceil(dp * sqrt(n))
if mp == None:
m = ceil(sqrt(n)) + 4
else:
m = ceil(mp * sqrt(n))
B = generate_basis_for_logarithm_finding(
p, u=[x], d=d, threads=threads, verbose=verbose
)
if verbose:
print("")
simulator = Simulator(B, threads=threads, verbose=verbose)
# Use the simulator to sample vectors.
if verbose:
print("")
print("** Using the simulator to sample vectors...")
print("")
R = get_regev_R(C, n)
samples = simulator.sample_vectors_with_failure_rate(
R, m=m, failure_rate=failure_rate, verbose=verbose
)
# Solve the vectors sampled for the logarithm.
if verbose:
print("")
print("** Post-processing the sampled vectors to find " + \
"e = log_{g_max}(x)...")
print("")
e_x = solve_samples_for_logarithm_with_precomputation(
samples,
g_max,
x,
p,
R,
block_size=block_size,
verbose=verbose)
# 2. Solve for e_g = log_{g_max}(g).
# Setup the simulator.
if verbose:
print("")
print("** Setting up the simulator for e = log_{g_max}(g)...")
print("")
B = generate_basis_for_logarithm_finding(
p, u=[g], d=d, threads=threads, verbose=verbose
)
if verbose:
print("")
simulator = Simulator(B, threads=threads, verbose=verbose)
# Use the simulator to sample vectors.
if verbose:
print("")
print("** Using the simulator to sample vectors...")
print("")
samples = simulator.sample_vectors_with_failure_rate(
R, m=m, failure_rate=failure_rate, verbose=verbose
)
# Solve the vectors sampled for the logarithm.
if verbose:
print("")
print("** Post-processing the sampled vectors to find " + \
"e = log_{g_max}(g)...")
print("")
e_g = solve_samples_for_logarithm_with_precomputation(
samples,
g_max,
g,
p,
R,
block_size=block_size,
verbose=verbose)
# 3. Solve for the logarithm e = e_x / e_g (mod r) where r is assumed known.
if verbose:
print("")
print("** Combining the results to solve for e = log_{g}(x)...")
print("")
r = find_smooth_order_mod_p(g, p)
R = IntegerModRing(r)
e_found = R(e_x) / R(e_g)
if verbose:
print("Found e =", e_found)
return e_found == e
def test_logarithm_finding_in_schnorr_group_with_precomputation(
l=2048,
k=224,
*,
B=DEFAULT_BOUND_B,
C=DEFAULT_CONSTANT_C,
dp=1,
mp=None,
failure_rate=0,
block_size=DEFAULT_BLOCK_SIZE,
threads=DEFAULT_THREADS,
verbose=True):
"""
@brief A convenience function for testing the simulator for the quantum
algorithm in [EG23p], and the associated classical post-processing,
with respect to computing discrete logarithms in simulated
Schnorr groups with pre-computation.
[EG23p] Ekerå, M. and Gärtner, J.: "Extending Regev's factoring algorithm
to compute discrete logarithms".
ArXiv 2311.05545v2 (2023).
This function first picks domain parameters for a simulated Schnorr group.
Specifically, this function first samples an l-bit prime p such that p - 1
is B-smooth for some small bound B (to enable efficient simulation), and
such that p - 1 = 2 * u * r where r is of length approximately k bits. It
then picks a generator g that is of order r.
This function also sets up a problem instance x = g^e mod p by sampling e
uniformly at random from [0, r) and computing x.