-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
2914 lines (2717 loc) · 134 KB
/
Copy pathindex.html
File metadata and controls
2914 lines (2717 loc) · 134 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
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.10.0" />
<title>cryptanalysis API documentation</title>
<meta name="description" content="" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Package <code>cryptanalysis</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">from .spn import SPN, rotate_left, gen_pbox
from .characteristic_searcher import CharacteristicSearcher
from .linear_cryptanalysis import LinearCryptanalysis
from .differential_cryptanalysis import DifferentialCryptanalysis
from .utils import parity, calculate_linear_bias, calculate_difference_table
__all__ = ["CharacteristicSearcher", "LinearCryptanalysis",
"DifferentialCryptanalysis", "SPN", "rotate_left", "gen_pbox",
"parity", "calculate_linear_bias", "calculate_difference_table"]</code></pre>
</details>
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="cryptanalysis.characteristic_searcher" href="characteristic_searcher.html">cryptanalysis.characteristic_searcher</a></code></dt>
<dd>
<div class="desc"><p>characteristic_searcher
…</p></div>
</dd>
<dt><code class="name"><a title="cryptanalysis.cryptanalysis" href="cryptanalysis.html">cryptanalysis.cryptanalysis</a></code></dt>
<dd>
<div class="desc"><p>Module for performing cryptanalysis on Substitution Permutation Network cipher …</p></div>
</dd>
<dt><code class="name"><a title="cryptanalysis.differential_cryptanalysis" href="differential_cryptanalysis.html">cryptanalysis.differential_cryptanalysis</a></code></dt>
<dd>
<div class="desc"><p>Module for performing differential cryptanalysis on Substitution Permutation Network based ciphers …</p></div>
</dd>
<dt><code class="name"><a title="cryptanalysis.linear_cryptanalysis" href="linear_cryptanalysis.html">cryptanalysis.linear_cryptanalysis</a></code></dt>
<dd>
<div class="desc"><p>Module for performing linear cryptanalysis on Substitution Permutation Network based ciphers …</p></div>
</dd>
<dt><code class="name"><a title="cryptanalysis.spn" href="spn.html">cryptanalysis.spn</a></code></dt>
<dd>
<div class="desc"><p>The <code><a title="cryptanalysis.spn" href="spn.html">cryptanalysis.spn</a></code> module implements the Substitution-Permutation Network (SPN) encryption algorithm …</p></div>
</dd>
<dt><code class="name"><a title="cryptanalysis.utils" href="utils.html">cryptanalysis.utils</a></code></dt>
<dd>
<div class="desc"><p>The <code><a title="cryptanalysis.utils" href="utils.html">cryptanalysis.utils</a></code> module provides utility functions for various operations …</p></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="cryptanalysis.calculate_difference_table"><code class="name flex">
<span>def <span class="ident">calculate_difference_table</span></span>(<span>sbox)</span>
</code></dt>
<dd>
<div class="desc"><p>Calculates the difference distribution table for an S-box.</p>
<p>This method calculates the difference table for an S-box. It iterates
over all possible input and input difference pairs and counts the number of
output differences for each input difference.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>sbox</code></strong> : <code>list</code></dt>
<dd>A list of integers representing the S-box.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>Counter</code></dt>
<dd>A Counter dictionary containing the count of output differences for each input difference.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def calculate_difference_table(sbox):
"""Calculates the difference distribution table for an S-box.
This method calculates the difference table for an S-box. It iterates
over all possible input and input difference pairs and counts the number of
output differences for each input difference.
Args:
sbox (list): A list of integers representing the S-box.
Returns:
Counter: A Counter dictionary containing the count of output differences for each input difference.
"""
n = len(sbox)
bias = Counter()
for inp_diff in tqdm(range(n), desc='calculating sbox differences'):
for inp in range(n):
out_diff = sbox[inp] ^ sbox[inp ^ inp_diff]
bias[(inp_diff, out_diff)] += 1
return bias</code></pre>
</details>
</dd>
<dt id="cryptanalysis.calculate_linear_bias"><code class="name flex">
<span>def <span class="ident">calculate_linear_bias</span></span>(<span>sbox, no_sign=True, fraction=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Calculates the linear bias of an S-box.</p>
<p>This method calculates the linear bias of an S-box. It iterates over
all possible input and output mask pairs and computes the linear bias using
the Cryptanalysis.parity method.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>sbox</code></strong> : <code>list</code></dt>
<dd>A list of integers representing the S-box.</dd>
<dt><strong><code>no_sign</code></strong> : <code>bool</code>, optional</dt>
<dd>If True, the absolute value of the bias is returned. Defaults to True.</dd>
<dt><strong><code>fraction</code></strong> : <code>bool</code>, optional</dt>
<dd>If True, the bias is returned as a fraction. Defaults to False.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>Counter</code></dt>
<dd>A Counter dictionary containing the linear biases for each input and output mask pair.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def calculate_linear_bias(sbox, no_sign=True, fraction=False):
"""Calculates the linear bias of an S-box.
This method calculates the linear bias of an S-box. It iterates over
all possible input and output mask pairs and computes the linear bias using
the Cryptanalysis.parity method.
Args:
sbox (list): A list of integers representing the S-box.
no_sign (bool, optional): If True, the absolute value of the bias is returned. Defaults to True.
fraction (bool, optional): If True, the bias is returned as a fraction. Defaults to False.
Returns:
Counter: A Counter dictionary containing the linear biases for each input and output mask pair.
"""
n = len(sbox)
bias = Counter({(i, j): -(n // 2) for i in range(n) for j in range(n)})
for imask in tqdm(range(n), desc='calculating sbox bias'):
for omask in range(n):
for i in range(n):
bias[(imask, omask)] += parity((sbox[i] & omask) ^ (i & imask)) ^ 1
if no_sign:
for i in bias:
bias[i] = abs(bias[i])
if fraction:
for i in bias:
bias[i] /= n
return bias</code></pre>
</details>
</dd>
<dt id="cryptanalysis.gen_pbox"><code class="name flex">
<span>def <span class="ident">gen_pbox</span></span>(<span>s, n)</span>
</code></dt>
<dd>
<div class="desc"><p>Generate a balanced permutation box for an SPN.</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>s</code></strong> : <code>int</code></dt>
<dd>Number of bits per S-box.</dd>
<dt><strong><code>n</code></strong> : <code>int</code></dt>
<dd>Number of S-boxes.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code> of <code>int</code></dt>
<dd>The generated P-box.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def gen_pbox(s, n):
"""
Generate a balanced permutation box for an SPN.
Parameters
----------
s : int
Number of bits per S-box.
n : int
Number of S-boxes.
Returns
-------
list of int
The generated P-box.
"""
return [(s * i + j) % (n * s) for j in range(s) for i in range(n)]</code></pre>
</details>
</dd>
<dt id="cryptanalysis.parity"><code class="name flex">
<span>def <span class="ident">parity</span></span>(<span>x)</span>
</code></dt>
<dd>
<div class="desc"><p>Calculates the parity of an integer.</p>
<p>This method calculates the parity of an integer by counting the number
of set bits in the binary representation of the integer. It returns 0 if the
number of set bits is even, and 1 otherwise.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>x</code></strong> : <code>int</code></dt>
<dd>The input value for which the parity is calculated.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>int</code></dt>
<dd>0 if the number of set bits is even, 1 otherwise.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def parity(x):
"""Calculates the parity of an integer.
This method calculates the parity of an integer by counting the number
of set bits in the binary representation of the integer. It returns 0 if the
number of set bits is even, and 1 otherwise.
Args:
x (int): The input value for which the parity is calculated.
Returns:
int: 0 if the number of set bits is even, 1 otherwise.
"""
res = 0
while x:
res ^= 1
x &= (x - 1)
return res</code></pre>
</details>
</dd>
<dt id="cryptanalysis.rotate_left"><code class="name flex">
<span>def <span class="ident">rotate_left</span></span>(<span>val, shift, mod)</span>
</code></dt>
<dd>
<div class="desc"><p>Rotate the bits of the value to the left by the shift amount.</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>val</code></strong> : <code>int</code></dt>
<dd>The value to be rotated.</dd>
<dt><strong><code>shift</code></strong> : <code>int</code></dt>
<dd>The number of places to shift the value to the left.</dd>
<dt><strong><code>mod</code></strong> : <code>int</code></dt>
<dd>The modulo to be applied on the result.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>int</code></dt>
<dd>The rotated value.</dd>
</dl>
<h2 id="notes">Notes</h2>
<p>The function rotates the bits of the value to the left by the shift amount,
wrapping the bits that overflow. The result is then masked by (1<<mod)-1
to only keep the mod number of least significant bits.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def rotate_left(val, shift, mod):
"""
Rotate the bits of the value to the left by the shift amount.
Parameters
----------
val : int
The value to be rotated.
shift : int
The number of places to shift the value to the left.
mod : int
The modulo to be applied on the result.
Returns
-------
int
The rotated value.
Notes
-----
The function rotates the bits of the value to the left by the shift amount,
wrapping the bits that overflow. The result is then masked by (1<<mod)-1
to only keep the mod number of least significant bits.
"""
shift = shift % mod
return (val << shift | val >> (mod - shift)) & ((1 << mod) - 1)</code></pre>
</details>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="cryptanalysis.CharacteristicSearcher"><code class="flex name class">
<span>class <span class="ident">CharacteristicSearcher</span></span>
<span>(</span><span>sbox, pbox, num_rounds, mode='linear')</span>
</code></dt>
<dd>
<div class="desc"><p>A class for finding characteristics (linear or differential) of a substitution
permutation network with provided S-box and P-box with a given number of rounds.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>sbox</code></strong></dt>
<dd>A list representing the substitution box.</dd>
<dt><strong><code>pbox</code></strong></dt>
<dd>A list representing the permutation box.</dd>
<dt><strong><code>num_rounds</code></strong></dt>
<dd>An integer representing the number of rounds.</dd>
<dt><strong><code>block_size</code></strong></dt>
<dd>An integer representing the number of bits in the block.</dd>
<dt><strong><code>box_size</code></strong></dt>
<dd>An integer representing the size of the S-box in bits.</dd>
<dt><strong><code>num_blocks</code></strong></dt>
<dd>An integer representing the number of sboxes in a block</dd>
<dt><strong><code>mode</code></strong></dt>
<dd>A string representing the mode, which can be 'linear' or 'differential'.</dd>
<dt><strong><code>bias</code></strong></dt>
<dd>A Counter dictionary representing linear or differential bias
of sbox input/output pairs</dd>
<dt><strong><code>solutions</code></strong></dt>
<dd>A dictionary containing list of valid characteristic masks for a given
set of included and excluded blocks</dd>
<dt><strong><code>solver</code></strong></dt>
<dd>SMT solver (optimize) instance to search the characteristics</dd>
</dl>
<p>Initializes the CharacteristicSolver with the given sbox, pbox, num_rounds and mode.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>sbox</code></strong> : <code>list</code></dt>
<dd>The substitution box.</dd>
<dt><strong><code>pbox</code></strong> : <code>list</code></dt>
<dd>The permutation box.</dd>
<dt><strong><code>num_rounds</code></strong> : <code>int</code></dt>
<dd>The number of rounds.</dd>
<dt><strong><code>mode</code></strong> : <code>str</code>, optional</dt>
<dd>The mode of operation. Defaults to 'linear'.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class CharacteristicSearcher:
"""A class for finding characteristics (linear or differential) of a substitution
permutation network with provided S-box and P-box with a given number of rounds.
Attributes:
sbox: A list representing the substitution box.
pbox: A list representing the permutation box.
num_rounds: An integer representing the number of rounds.
block_size: An integer representing the number of bits in the block.
box_size: An integer representing the size of the S-box in bits.
num_blocks: An integer representing the number of sboxes in a block
mode: A string representing the mode, which can be 'linear' or 'differential'.
bias: A Counter dictionary representing linear or differential bias
of sbox input/output pairs
solutions: A dictionary containing list of valid characteristic masks for a given
set of included and excluded blocks
solver: SMT solver (optimize) instance to search the characteristics
"""
def __init__(self, sbox, pbox, num_rounds, mode='linear'):
"""Initializes the CharacteristicSolver with the given sbox, pbox, num_rounds and mode.
Args:
sbox (list): The substitution box.
pbox (list): The permutation box.
num_rounds (int): The number of rounds.
mode (str, optional): The mode of operation. Defaults to 'linear'.
"""
self.sbox = sbox
self.pbox = pbox
self.num_rounds = num_rounds
self.block_size = len(pbox)
self.box_size = int(log2(len(sbox)))
self.num_blocks = len(pbox) // self.box_size
self.mode = mode
if mode == 'linear':
self.bias = calculate_linear_bias(sbox)
elif mode == 'differential':
self.bias = calculate_difference_table(sbox)
self.solutions = defaultdict(list)
self.solver = Optimize()
self.prune_level = 0
self.sboxf = None
self.inps = None
self.oups = None
self.bv_inp_masks = None
self.bv_oup_masks = None
self.objectives = None
def initialize_sbox_structure(self):
"""Initializes the S-box structure for the cryptographic solver.
This method sets up the structure of the S-box by creating an optimized solver,
initializing input and output bit vectors for each round, and adding
constraints for the solver. It also creates a concatenated view of the input
and output layers for further processing.
"""
n = self.box_size
self.inps = [[BitVec('r{}_i{}'.format(r, i), n) for i in range(
self.num_blocks)] for r in range(self.num_rounds + 1)]
self.oups = [[BitVec('r{}_o{}'.format(r, i), n) for i in range(
self.num_blocks)] for r in range(self.num_rounds)]
# permutation of output of sboxes are inputs of next round
for i in range(self.num_rounds):
if self.num_blocks == 1:
self.solver.add(self.bitvec_permutation(
self.oups[i][0], self.inps[i + 1][0]))
else:
self.solver.add(self.bitvec_permutation(
Concat(self.oups[i]), Concat(self.inps[i + 1])))
# all first layer inputs should not be 0
self.solver.add(
Not(And(*[self.inps[0][i] == 0 for i in range(self.num_blocks)])))
for r in range(self.num_rounds):
for i in range(self.num_blocks):
# if sbox has input, it should have output
self.solver.add(
Implies(
self.inps[r][i] != 0,
self.oups[r][i] != 0))
# if sbox has no input it should not have any output
self.solver.add(
Implies(
self.inps[r][i] == 0,
self.oups[r][i] == 0))
# just a concatanated view of the input and output layers
if self.num_blocks == 1:
self.bv_inp_masks = [self.inps[i][0]
for i in range(self.num_rounds + 1)]
self.bv_oup_masks = [self.oups[i][0]
for i in range(self.num_rounds)]
else:
self.bv_inp_masks = [Concat(self.inps[i])
for i in range(self.num_rounds + 1)]
self.bv_oup_masks = [Concat(self.oups[i])
for i in range(self.num_rounds)]
def bitvec_permutation(self, inp, oup):
"""Performs bit vector permutation based on pbox.
Args:
inp (BitVec): The input bit vector.
oup (BitVec): The output bit vector.
Returns:
list: A list of constraints for the permutation.
"""
pn = len(self.pbox)
constraints = []
for i, v in enumerate(self.pbox):
constraints.append(
Extract(pn - 1 - i, pn - 1 - i, inp) ==
Extract(pn - 1 - v, pn - 1 - v, oup)
)
return constraints
def initialize_objectives(self):
"""Initializes the objective functions for the cryptographic solver.
The method sets up four types of objective functions: 'original_linear',
'reduced', 'differential', and 'linear'. These objective functions are
used to guide the solver in finding the optimal solution. Each objective
function is associated with a lambda function that calculates the objective
value for a given number of rounds.
'reduced' objective is called for both linear and differential search
Other objective functions are just there for reference and easy evaluation
of bias directly from the model
"""
self.objectives = {
# the actual objective, which is just product of bias [0,1/2]
'original_linear': lambda rounds: 2**(self.num_blocks * rounds - 1) * Product([self.sboxf(
self.inps[i // self.num_blocks][i % self.num_blocks],
self.oups[i // self.num_blocks][i % self.num_blocks])
for i in range(self.num_blocks * rounds)
]),
# reducing optimization problem of product to sums
'reduced': lambda rounds: sum([
self.sboxf(
self.inps[i // self.num_blocks][i % self.num_blocks],
self.oups[i // self.num_blocks][i % self.num_blocks])
for i in range(self.num_blocks * rounds)
]),
# objective when the input biases are [0,2**n] just the final
# division
'differential': lambda rounds: Product([
self.sboxf(
self.inps[i // self.num_blocks][i % self.num_blocks],
self.oups[i // self.num_blocks][i % self.num_blocks])
for i in range(self.num_blocks * rounds)
]) / ((2**self.box_size)**(self.num_blocks * rounds)),
'linear': lambda rounds: 2**(self.num_blocks * rounds - 1) * Product([
self.sboxf(
self.inps[i // self.num_blocks][i % self.num_blocks],
self.oups[i // self.num_blocks][i % self.num_blocks])
for i in range(self.num_blocks * rounds)
]) / ((2**self.box_size)**(self.num_blocks * rounds))
}
def add_bias_constraints(self, prune_level):
"""Adds bias constraints to the solver based on the biases of the S-box.
This method adds constraints to the solver that are based on the biases of the S-box.
If the bias of a particular input-output pair is greater than or equal to 2**prune_level,
the method adds a constraint that the S-box function of the pair is equal to the bias.
Otherwise, it adds a constraint that the S-box function of the pair is 0. This helps in
pruning the search space of the solver.
Args:
prune_level (int): The level at which to prune the biases.
"""
for i in range(2**self.box_size):
for j in range(2**self.box_size):
# just some pruning of very small biases
if self.bias[(i, j)] >= 2**(prune_level):
self.solver.add(self.sboxf(i, j) == self.bias[(i, j)])
else:
self.solver.add(self.sboxf(i, j) == 0)
for r in range(self.num_rounds):
for i in range(self.num_blocks):
# skip taking input/outputs with no bias
self.solver.add(
Implies(
And(self.inps[r][i] != 0, self.oups[r][i] != 0),
self.sboxf(self.inps[r][i], self.oups[r][i]) != 0
)
)
def init_characteristic_solver(self, prune_level=-1):
"""Initializes the S-box structure, S-box function, objective functions, and pruning level.
This method initializes the structure of the S-box, the S-box function,
and the objective functions for the solver. It also sets the pruning level
for the solver. If no pruning level is provided, the method will search for
the best pruning level.
Args:
prune_level (int, optional): The level at which to prune the biases.
If not provided or less than 0, the method will search for the best pruning level.
"""
self.initialize_sbox_structure()
self.sboxf = Function(
'sbox', BitVecSort(
self.box_size), BitVecSort(
self.box_size), RealSort())
self.initialize_objectives()
assert self.solver.check()
if prune_level < 0:
print("searching best pruning level")
low, high = 0, len(self.sbox) // 4
while low <= high:
mid = (low + high) // 2
print("trying pruning", mid)
self.solver.push()
self.solver.set(timeout=10000)
self.add_bias_constraints(mid)
if self.solver.check() == sat:
print("success")
low = mid + 1
else:
print("failure")
high = mid - 1
self.solver.pop()
self.solver.set(timeout=0)
print("best pruning", high)
self.prune_level = high
self.add_bias_constraints(high)
else:
self.add_bias_constraints(prune_level)
if self.solver.check() == sat:
self.prune_level = prune_level
else:
print("Provided pruning level unsat, searching optimal pruning")
self.init_characteristic_solver(-1) # search best pruning
def solve_for_blocks(self, include_blocks=(), exclude_blocks=(),
num_rounds=0,
num_sols=1,
display_paths=True):
"""Solves the characteristic for the specified blocks and maximizes the objective function.
This method searches the characteristic for the specified blocks,
maximizes the objective function, and returns the solutions.
The blocks to include and exclude in the characteristic can be specified.
The number of rounds and the number of solutions can also be specified.
Args:
include_blocks (list, optional): The blocks to definitely include in the characteristic.
exclude_blocks (list, optional): The blocks to definitely exclude in the characteristic.
num_rounds (int, optional): The number of rounds for which to solve the characteristic.
If not provided or 0, the number of rounds will be set to the
number of rounds of the solver.
num_sols (int, optional): The number of solutions to return.
display_paths (bool, optional): Whether to display the paths of the solutions.
Returns:
list: A list of tuples. Each tuple contains the input masks, the output masks, and the
calculated bias for a solution.
"""
if num_rounds == 0:
num_rounds = self.num_rounds
else:
# cap to initialized struct
num_rounds = min(self.num_rounds, num_rounds)
while len(self.solver.objectives()):
self.solver.pop() # remove any previous include/exclude block constraints
self.solver.push() # set this as the checkpoint
# specify which blocks to definitely include in the characteristic
for i in include_blocks:
self.solver.add(self.inps[num_rounds - 1][i] != 0)
# specify which blocks to definitely exclude in the characteristic
for i in exclude_blocks:
self.solver.add(self.inps[num_rounds - 1][i] == 0)
# print(include_blocks, exclude_blocks)
# if a block is neither in include_blocks or exclude_blocks
# the solver finds the best path which may or may not set it to active
self.solver.maximize(self.objectives['reduced'](num_rounds))
solutions = self.get_masks(num_rounds, num_sols, display_paths)
self.solutions[(tuple(sorted(include_blocks)),
tuple(sorted(exclude_blocks)))].extend(solutions)
return [(inp_masks[0], inp_masks[-1], calc_bias)
for inp_masks, _, calc_bias, _ in solutions]
def search_best_masks(self, tolerance=1, choose_best=10, display_paths=True):
"""Searches for the best masks with the highest total bias and limited undiscovered active blocks.
This method searches for the best masks with the highest total bias and a limited number
of undiscovered active blocks.
Args:
tolerance (int, optional): The maximum number of undiscovered active blocks allowed.
choose_best (int, optional): The number of best masks to choose from.
display_paths (bool, optional): Whether to display the characteristic paths
(containing the bits involved) of the solutions.
Returns:
list: A list of tuples. Each tuple contains the input masks, the output masks, and the
total bias for a solution.
"""
self.init_characteristic_solver()
nr = self.num_rounds
discovered = [False for _ in range(self.num_blocks)]
def istolerable(x):
return sum((not i) and j
for i, j in zip(discovered, x[3])) in range(1, tolerance + 1)
masks = []
while self.solver.check() == sat:
curr_masks = self.get_masks(self.num_rounds, choose_best, display_paths=False)
for i in curr_masks:
self.solutions[i[2]].append(i)
curr_masks = list(filter(istolerable, curr_masks))
if len(curr_masks) > 0:
inp_masks, oup_masks, total_bias, active = max(
curr_masks, key=lambda x: (x[2], -sum(x[3])))
if display_paths:
self.print_bitrelations(inp_masks, oup_masks)
print("total bias:", total_bias)
print()
masks.append((inp_masks[0], inp_masks[nr - 1], total_bias))
for i, v in enumerate(discovered):
if (not v) and active[i]:
discovered[i] = True
print("discovered", "".join(map(lambda x: str(int(x)), discovered)))
# dont discover biases where all the active blocks come from discovered blocks
# i.e. if all the active blocks come from discovered blocks,
# it means, all the undiscovered blocks are inactive
# i.e it should not be the case where all the undiscovered blocks are
# inactive i.e 0
self.solver.add(Not(And(
[self.inps[nr - 1][i] == 0 for i, v in enumerate(discovered) if not v]
)))
return masks
def search_exclusive_masks(self, prune_level=-1, repeat=1):
"""Searches for the masks for each block by including only one block and excluding all the others.
This method searches for the masks for each block by including only one block and excluding
all the others.
Args:
prune_level (int, optional): The level at which to prune the biases.
repeat (int, optional): The number of times to repeat the search for each block.
Returns:
list: A list of tuples. Each tuple contains the input masks, the output masks, and the
total bias for a solution.
"""
self.init_characteristic_solver(prune_level)
masks = []
for i in range(self.num_blocks):
include_blocks = {i}
exclude_blocks = set(range(self.num_blocks)) - include_blocks
masks.extend(self.solve_for_blocks(include_blocks, exclude_blocks, num_sols=repeat))
return masks
def get_masks(self, num_rounds, n=1, display_paths=True):
"""Returns the input masks, output masks, total bias, and active blocks of the solutions.
This method returns the input masks, output masks, total bias, and active blocks of the solutions.
Args:
num_rounds (int): The number of rounds for which to get the masks.
n (int, optional): The number of masks to get.
display_paths (bool, optional): Whether to display the paths of the solutions.
Returns:
list: A list of tuples. Each tuple contains the input masks, the output masks, the total bias,
and the active blocks for a solution.
"""
masks = []
for m in islice(all_smt(self.solver, [self.bv_inp_masks[num_rounds - 1]]), n):
inp_masks = [m.eval(i).as_long()
for i in self.bv_inp_masks[:num_rounds]]
oup_masks = [m.eval(i).as_long()
for i in self.bv_oup_masks[:num_rounds]]
total_bias = m.eval(
self.objectives[self.mode](num_rounds)).as_fraction()
active = [m.eval(i).as_long() != 0 for i in self.inps[num_rounds - 1]]
if display_paths:
self.print_bitrelations(inp_masks, oup_masks)
print("total bias:", total_bias)
print()
masks.append((inp_masks, oup_masks, total_bias, active))
return masks
def print_bitrelations(self, inp_masks, out_masks):
"""
Print the input and output masks of a block cipher in a formatted manner.
:param inp_masks: List of integers, input masks for each round.
:param out_masks: List of integers, output masks for each round.
"""
s = self.box_size
n = self.num_blocks * s
def bin_sep(val):
v = bin(val)[2:].zfill(n)
return "|".join(v[i:i + s] for i in range(0, n, s))
rounds = len(out_masks)
for i in range(rounds):
imask, omask = inp_masks[i], out_masks[i]
print(bin_sep(imask))
print(' '.join(['-' * s] * (n // s)))
print(bin_sep(omask))
print()
print(bin_sep(inp_masks[-1]))</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="cryptanalysis.CharacteristicSearcher.add_bias_constraints"><code class="name flex">
<span>def <span class="ident">add_bias_constraints</span></span>(<span>self, prune_level)</span>
</code></dt>
<dd>
<div class="desc"><p>Adds bias constraints to the solver based on the biases of the S-box.</p>
<p>This method adds constraints to the solver that are based on the biases of the S-box.
If the bias of a particular input-output pair is greater than or equal to 2**prune_level,
the method adds a constraint that the S-box function of the pair is equal to the bias.
Otherwise, it adds a constraint that the S-box function of the pair is 0. This helps in
pruning the search space of the solver.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>prune_level</code></strong> : <code>int</code></dt>
<dd>The level at which to prune the biases.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def add_bias_constraints(self, prune_level):
"""Adds bias constraints to the solver based on the biases of the S-box.
This method adds constraints to the solver that are based on the biases of the S-box.
If the bias of a particular input-output pair is greater than or equal to 2**prune_level,
the method adds a constraint that the S-box function of the pair is equal to the bias.
Otherwise, it adds a constraint that the S-box function of the pair is 0. This helps in
pruning the search space of the solver.
Args:
prune_level (int): The level at which to prune the biases.
"""
for i in range(2**self.box_size):
for j in range(2**self.box_size):
# just some pruning of very small biases
if self.bias[(i, j)] >= 2**(prune_level):
self.solver.add(self.sboxf(i, j) == self.bias[(i, j)])
else:
self.solver.add(self.sboxf(i, j) == 0)
for r in range(self.num_rounds):
for i in range(self.num_blocks):
# skip taking input/outputs with no bias
self.solver.add(
Implies(
And(self.inps[r][i] != 0, self.oups[r][i] != 0),
self.sboxf(self.inps[r][i], self.oups[r][i]) != 0
)
)</code></pre>
</details>
</dd>
<dt id="cryptanalysis.CharacteristicSearcher.bitvec_permutation"><code class="name flex">
<span>def <span class="ident">bitvec_permutation</span></span>(<span>self, inp, oup)</span>
</code></dt>
<dd>
<div class="desc"><p>Performs bit vector permutation based on pbox.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>inp</code></strong> : <code>BitVec</code></dt>
<dd>The input bit vector.</dd>
<dt><strong><code>oup</code></strong> : <code>BitVec</code></dt>
<dd>The output bit vector.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>A list of constraints for the permutation.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def bitvec_permutation(self, inp, oup):
"""Performs bit vector permutation based on pbox.
Args:
inp (BitVec): The input bit vector.
oup (BitVec): The output bit vector.
Returns:
list: A list of constraints for the permutation.
"""
pn = len(self.pbox)
constraints = []
for i, v in enumerate(self.pbox):
constraints.append(
Extract(pn - 1 - i, pn - 1 - i, inp) ==
Extract(pn - 1 - v, pn - 1 - v, oup)
)
return constraints</code></pre>
</details>
</dd>
<dt id="cryptanalysis.CharacteristicSearcher.get_masks"><code class="name flex">
<span>def <span class="ident">get_masks</span></span>(<span>self, num_rounds, n=1, display_paths=True)</span>
</code></dt>
<dd>
<div class="desc"><p>Returns the input masks, output masks, total bias, and active blocks of the solutions.</p>
<p>This method returns the input masks, output masks, total bias, and active blocks of the solutions.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>num_rounds</code></strong> : <code>int</code></dt>
<dd>The number of rounds for which to get the masks.</dd>
<dt><strong><code>n</code></strong> : <code>int</code>, optional</dt>
<dd>The number of masks to get.</dd>
<dt><strong><code>display_paths</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to display the paths of the solutions.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>A list of tuples. Each tuple contains the input masks, the output masks, the total bias,
and the active blocks for a solution.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_masks(self, num_rounds, n=1, display_paths=True):
"""Returns the input masks, output masks, total bias, and active blocks of the solutions.
This method returns the input masks, output masks, total bias, and active blocks of the solutions.
Args:
num_rounds (int): The number of rounds for which to get the masks.
n (int, optional): The number of masks to get.
display_paths (bool, optional): Whether to display the paths of the solutions.
Returns:
list: A list of tuples. Each tuple contains the input masks, the output masks, the total bias,
and the active blocks for a solution.
"""
masks = []
for m in islice(all_smt(self.solver, [self.bv_inp_masks[num_rounds - 1]]), n):
inp_masks = [m.eval(i).as_long()
for i in self.bv_inp_masks[:num_rounds]]
oup_masks = [m.eval(i).as_long()
for i in self.bv_oup_masks[:num_rounds]]
total_bias = m.eval(
self.objectives[self.mode](num_rounds)).as_fraction()
active = [m.eval(i).as_long() != 0 for i in self.inps[num_rounds - 1]]
if display_paths:
self.print_bitrelations(inp_masks, oup_masks)
print("total bias:", total_bias)
print()
masks.append((inp_masks, oup_masks, total_bias, active))
return masks</code></pre>
</details>
</dd>
<dt id="cryptanalysis.CharacteristicSearcher.init_characteristic_solver"><code class="name flex">
<span>def <span class="ident">init_characteristic_solver</span></span>(<span>self, prune_level=-1)</span>
</code></dt>
<dd>
<div class="desc"><p>Initializes the S-box structure, S-box function, objective functions, and pruning level.</p>
<p>This method initializes the structure of the S-box, the S-box function,
and the objective functions for the solver. It also sets the pruning level
for the solver. If no pruning level is provided, the method will search for
the best pruning level.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>prune_level</code></strong> : <code>int</code>, optional</dt>
<dd>The level at which to prune the biases.</dd>
</dl>
<p>If not provided or less than 0, the method will search for the best pruning level.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def init_characteristic_solver(self, prune_level=-1):
"""Initializes the S-box structure, S-box function, objective functions, and pruning level.
This method initializes the structure of the S-box, the S-box function,
and the objective functions for the solver. It also sets the pruning level
for the solver. If no pruning level is provided, the method will search for
the best pruning level.
Args:
prune_level (int, optional): The level at which to prune the biases.
If not provided or less than 0, the method will search for the best pruning level.
"""
self.initialize_sbox_structure()
self.sboxf = Function(
'sbox', BitVecSort(
self.box_size), BitVecSort(
self.box_size), RealSort())
self.initialize_objectives()
assert self.solver.check()
if prune_level < 0:
print("searching best pruning level")
low, high = 0, len(self.sbox) // 4
while low <= high:
mid = (low + high) // 2
print("trying pruning", mid)
self.solver.push()
self.solver.set(timeout=10000)
self.add_bias_constraints(mid)
if self.solver.check() == sat:
print("success")
low = mid + 1
else:
print("failure")
high = mid - 1
self.solver.pop()
self.solver.set(timeout=0)
print("best pruning", high)
self.prune_level = high
self.add_bias_constraints(high)
else:
self.add_bias_constraints(prune_level)
if self.solver.check() == sat:
self.prune_level = prune_level
else:
print("Provided pruning level unsat, searching optimal pruning")
self.init_characteristic_solver(-1) # search best pruning</code></pre>
</details>
</dd>
<dt id="cryptanalysis.CharacteristicSearcher.initialize_objectives"><code class="name flex">
<span>def <span class="ident">initialize_objectives</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Initializes the objective functions for the cryptographic solver.</p>
<p>The method sets up four types of objective functions: 'original_linear',