kryptools 0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kryptools-0.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Gerald Teschl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
kryptools-0.1/PKG-INFO ADDED
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.1
2
+ Name: kryptools
3
+ Version: 0.1
4
+ Summary: Implemenation of same basic algorithms used in cryptography.
5
+ Author-email: Gerald Teschl <gerald.teschl@univie.ac.at>
6
+ Project-URL: Homepage, https://github.com/teschlg/kryptools
7
+ Project-URL: Issues, https://github.com/teschlg/kryptools/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+
15
+ # kryptools
16
+ Gerald Teschl <Gerald.Teschl@univie.ac.at>
17
+
18
+ This package was written for my course on cryptography. Consequently its intention is
19
+ mainly educational, that is, to show how basic algorithms are implemented. In particular,
20
+ you are welcome to read (and modify) the source. Any suggestions on how to make the
21
+ code more readable or make it better are welcome. However, my main goal is to keep
22
+ it simple and readability will be preferred over small speed improvements.
23
+
24
+ The tools contained are:
25
+
26
+ * number theory: sqrt modulo primes, crt, continued fractions, etc.
27
+ * primes: Sieve of Erathostenes, primality tests
28
+ * solvers for discrete logarithms (naive, Pollard rho, Shanks baby step/giant step, index calculus, quadratic sieve)
29
+ * integer factorization (Pollard p-1, Lentra's ECM, Dixon, basic quadratic sieve)
30
+ * linear algebra: Hermite normal form, Gram-Schmidt
31
+ * lattices: Babai rounding/nearest plane, lattice reduction
32
+
33
+ * Matrix: a class for Matrices (inverse, det, reduced echelon form, etc.)
34
+ * Poly: a class for polynomials (division, modulo)
35
+ * Zmod: a class for the ring of integers modulo an integer
@@ -0,0 +1,21 @@
1
+ # kryptools
2
+ Gerald Teschl <Gerald.Teschl@univie.ac.at>
3
+
4
+ This package was written for my course on cryptography. Consequently its intention is
5
+ mainly educational, that is, to show how basic algorithms are implemented. In particular,
6
+ you are welcome to read (and modify) the source. Any suggestions on how to make the
7
+ code more readable or make it better are welcome. However, my main goal is to keep
8
+ it simple and readability will be preferred over small speed improvements.
9
+
10
+ The tools contained are:
11
+
12
+ * number theory: sqrt modulo primes, crt, continued fractions, etc.
13
+ * primes: Sieve of Erathostenes, primality tests
14
+ * solvers for discrete logarithms (naive, Pollard rho, Shanks baby step/giant step, index calculus, quadratic sieve)
15
+ * integer factorization (Pollard p-1, Lentra's ECM, Dixon, basic quadratic sieve)
16
+ * linear algebra: Hermite normal form, Gram-Schmidt
17
+ * lattices: Babai rounding/nearest plane, lattice reduction
18
+
19
+ * Matrix: a class for Matrices (inverse, det, reduced echelon form, etc.)
20
+ * Poly: a class for polynomials (division, modulo)
21
+ * Zmod: a class for the ring of integers modulo an integer
@@ -0,0 +1,115 @@
1
+ """
2
+ Ring of intergers modulo `n`.
3
+ """
4
+
5
+ class Zmod:
6
+ """
7
+ Ring of intergers modulo `n`.
8
+
9
+ Example:
10
+
11
+ To define a finite Galois field modulo the prime 5 use
12
+ >>> gf=Zmod(5)
13
+
14
+ To declare 3 as an element of our Galois filed use
15
+ >>> gf(3)
16
+ 3 (mod 5)
17
+
18
+ The usual arithmetic operations are supported.
19
+ >>> gf(2) + gf(3)
20
+ 0 (mod 5)
21
+ """
22
+
23
+ def __init__(self, n: int, short: bool = False):
24
+ self.n = n
25
+ self.short = short
26
+
27
+ def __call__(self, x: int):
28
+ return ZmodPoint(x, self)
29
+
30
+ def __eq__(self, other):
31
+ if isinstance(other, self.__class__):
32
+ return self.n == other.n
33
+ return False
34
+
35
+ def __contains__(self, other: "ZmodPoint") -> bool:
36
+ return isinstance(other, ZmodPoint) and self.n == other.ring.n
37
+
38
+
39
+ class ZmodPoint:
40
+ "Represents a point in the ring Zmod."
41
+
42
+ def __init__(self, x: int, ring: "Zmod"):
43
+ if isinstance(x, self.__class__) and x.ring.n == ring.n:
44
+ self.x = int(x)
45
+ else:
46
+ self.x = int(x) % ring.n
47
+ self.ring = ring
48
+
49
+ def __repr__(self):
50
+ if self.ring.short:
51
+ return str(self.x)
52
+ return f"{self.x} (mod {self.ring.n})"
53
+
54
+ def __eq__(self, other):
55
+ if not isinstance(other, self.__class__) or self.ring != other.ring:
56
+ return False
57
+ return self.x == other.x
58
+
59
+ def __bool__(self):
60
+ return self.x != 0
61
+
62
+ def __int__(self):
63
+ return self.x
64
+
65
+ def sharp(self):
66
+ "Returns a symmetric (w.r.t. 0) representative."
67
+ tmp = (self.ring.n - 1) // 2
68
+ return (self.x + tmp) % self.ring.n - tmp
69
+
70
+ def __hash__(self):
71
+ return hash(self.x)
72
+
73
+ def __add__(self, other: "ZmodPoint") -> "ZmodPoint":
74
+ if isinstance(other, self.__class__) and self.ring == other.ring:
75
+ return self.__class__(self.x + other.x, self.ring)
76
+ if isinstance(other, int):
77
+ return self.__class__(self.x + other, self.ring)
78
+ return NotImplemented
79
+
80
+ def __radd__(self, scalar: int) -> "ZmodPoint":
81
+ return self.__class__(scalar + self.x, self.ring)
82
+
83
+ def __neg__(self) -> "ZmodPoint":
84
+ return self.__class__(-self.x, self.ring)
85
+
86
+ def __sub__(self, other: "ZmodPoint") -> "ZmodPoint":
87
+ if isinstance(other, self.__class__) and self.ring == other.ring:
88
+ return self.__class__(self.x - other.x, self.ring)
89
+ if isinstance(other, int):
90
+ return self.__class__(self.x - other, self.ring)
91
+ return NotImplemented
92
+
93
+ def __rsub__(self, scalar: int) -> "ZmodPoint":
94
+ return self.__class__(scalar - self.x, self.ring)
95
+
96
+ def __mul__(self, other: "ZmodPoint") -> "ZmodPoint":
97
+ if isinstance(other, self.__class__) and self.ring == other.ring:
98
+ return self.__class__(self.x * other.x, self.ring)
99
+ if isinstance(other, int):
100
+ return self.__class__(self.x * other, self.ring)
101
+ return NotImplemented
102
+
103
+ def __rmul__(self, scalar: int) -> "ZmodPoint":
104
+ return self.__class__(scalar * self.x, self.ring)
105
+
106
+ def __truediv__(self, other: "ZmodPoint") -> "ZmodPoint":
107
+ if not isinstance(other, self.__class__) or self.ring != other.ring:
108
+ return NotImplemented
109
+ return self.__class__(self.x * pow(other.x, -1, self.ring.n), self.ring)
110
+
111
+ def __rtruediv__(self, scalar: int) -> "ZmodPoint":
112
+ return self.__class__(scalar * pow(self.x, -1, self.ring.n), self.ring)
113
+
114
+ def __pow__(self, scalar: int) -> "ZmodPoint":
115
+ return self.__class__(pow(self.x, scalar, self.ring.n), self.ring)
@@ -0,0 +1,13 @@
1
+ """
2
+ Implemenation of same basic algorithms used in cryptography.
3
+ """
4
+
5
+ from .dlp import dlog
6
+ from .ec import EC_Weierstrass
7
+ from .factor import factorint
8
+ from .la import Matrix
9
+ from .lat import hermite_nf, gram_schmidt, lll
10
+ from .nt import cf, convergents, jacobi_symbol, sqrt_mod, euler_phi, order, carmichael_lambda
11
+ from .poly import Poly
12
+ from .primes import sieve_eratosthenes, isprime
13
+ from .Zmod import Zmod
@@ -0,0 +1,76 @@
1
+ """
2
+ Discrete Log Problem:
3
+ dlog(a, b, n) solve the discrete log problem a^x = b mod n
4
+ """
5
+
6
+
7
+ from math import gcd, log, sqrt
8
+ from .nt import crt, order
9
+ from .dlp_bsgs import dlog_bsgs
10
+ from .dlp_qs import dlog_qs
11
+ from .factor import factorint
12
+
13
+
14
+ def dlog_naive(a: int, b: int, n: int, m: int = None) -> int:
15
+ """Compute the discrete log_a(b) in Z_n of an element a of order m by exhaustive search."""
16
+ a %= n
17
+ b %= n
18
+ if not m:
19
+ m = n - 1
20
+ aa = 1
21
+ for i in range(m):
22
+ aa = (aa * a) % n
23
+ if aa == b:
24
+ return i + 1
25
+ return None # no solution
26
+
27
+ def _dlog_switch(a: int, b: int, n: int, m: int) -> int:
28
+ """Compute the discrete log_a(b) in Z_n of an element a of order m choosing an appropriate method."""
29
+ if m < 1000:
30
+ return dlog_naive(a, b, n, m)
31
+ elif log(m) - 6 < 2 * sqrt(log(n) * log(log(n))): # compare the theoreticaly expected running times ob bsgs and ic; the constant 6 is determined experimentally
32
+ return dlog_bsgs(a, b, n, m)
33
+ else:
34
+ return dlog_qs(a, b, n, m)
35
+
36
+ def _dlog_ph(a: int, b: int, n: int, q: int, k: int) -> int:
37
+ """Compute the discrete log_a(b) in Z_n of an element a of order q^k using Pohlig-Hellman reduction."""
38
+ if k == 1 or q**k < 10000:
39
+ return _dlog_switch(a, b, n, q**k)
40
+ aj = pow(a, q ** (k - 1), n)
41
+ a1 = aj
42
+ bj = pow(b, q ** (k - 1), n)
43
+ xj = _dlog_switch(a1, bj, n, q)
44
+ for j in range(2, k + 1):
45
+ aj = pow(a, q ** (k - j), n)
46
+ bj = pow(b, q ** (k - j), n)
47
+ yj = _dlog_switch(a1, bj * pow(aj, -xj, n) % n, n, q)
48
+ if yj is None:
49
+ return None
50
+ xj = xj + q ** (j - 1) * yj % q**j
51
+ return xj
52
+
53
+
54
+ def dlog(a: int, b: int, n: int, m: int = None) -> int:
55
+ """Compute the discrete log_a(b) in Z_n of an element a of order m using Pohlig-Hellman reduction."""
56
+ a %= n
57
+ b %= n
58
+ assert gcd(a, n) == 1, "a and n must be coprime."
59
+ assert gcd(b, n) == 1, "b and n must be coprime."
60
+ if m:
61
+ mf = factorint(m)
62
+ else:
63
+ m, mf = order(a, n, True)
64
+ assert pow(b, m, n) == 1, "DLP not solvable."
65
+ # We first use Pohlig-Hellman to split m into powers of prime factors
66
+ mm = []
67
+ ll = []
68
+ for pj, kj in mf.items():
69
+ aj = pow(a, m // pj**kj, n)
70
+ bj = pow(b, m // pj**kj, n)
71
+ l = _dlog_ph(aj, bj, n, pj, kj)
72
+ if l is None:
73
+ return None
74
+ mm += [pj**kj]
75
+ ll += [l]
76
+ return crt(ll, mm)
@@ -0,0 +1,29 @@
1
+ """
2
+ Discrete log solvers: Shanks' baby-step-giant-step algorithm
3
+ """
4
+
5
+ from math import isqrt
6
+
7
+
8
+ def dlog_bsgs(a: int, b: int, n: int, m: int = None) -> int:
9
+ """Compute the discrete log_a(b) in Z_n of an element a of order m using Shanks' baby-step-giant-step algorithm."""
10
+ a %= n
11
+ b %= n
12
+ if not m:
13
+ m = n - 1
14
+ mm = 1 + isqrt(m - 1)
15
+ # initialize baby_steps table
16
+ baby_steps = {}
17
+ baby_step = 1
18
+ for k in range(mm):
19
+ baby_steps[baby_step] = k
20
+ baby_step = baby_step * a % n
21
+
22
+ # now take the giant steps
23
+ giant_stride = pow(a, -mm, n)
24
+ giant_step = b
25
+ for l in range(mm):
26
+ if giant_step in baby_steps:
27
+ return l * mm + baby_steps[giant_step]
28
+ giant_step = giant_step * giant_stride % n
29
+ return None # no solution
@@ -0,0 +1,136 @@
1
+ """
2
+ Discrete log solvers: Index calculus
3
+ """
4
+
5
+ from math import gcd
6
+ from random import randint
7
+ from .primes import sieve_eratosthenes
8
+ from .dlp_qs import determine_factorbound, determine_trialdivison_bounds, is_smooth
9
+
10
+ def dlog_ic(a: int, b: int, n: int, m: int, pollard: bool = True, verbose: int = 0) -> int:
11
+ """Compute the discrete log_a(b) in Z_p of an element a of prime order m using Index Calculus."""
12
+
13
+ # assert isprime(m), "The order of a must be prime."
14
+ # assert n_order(a, n) == m, "The order of a is incorrect."
15
+ # assert pow(b, m, n) == 1, "The DLP is not solvable."
16
+
17
+ def find_relation(include_b: bool) -> None or list:
18
+ """Find a relation for b * a^x or a^x"""
19
+ nonlocal a, b, m, n, max_trys, factorbase, factorbase_len, smallprimes_len, pollard_k
20
+
21
+ x_max = m - 1
22
+ x_min = 0
23
+ if include_b:
24
+ x_min = 1
25
+ trys = 0
26
+ while trys < max_trys:
27
+ x = randint(x_min, x_max)
28
+ if include_b:
29
+ bax = b * pow(a ,x, n) % n
30
+ else:
31
+ bax = pow(a ,x, n)
32
+ relation = is_smooth(bax, factorbase, factorbase_len, smallprimes_len, pollard_k)
33
+ if relation:
34
+ break
35
+ trys += 1
36
+ else:
37
+ raise Exception(f"Sorry, Index Calculus failed to find a relation after {trys} trys.")
38
+ if verbose > 2:
39
+ if include_b:
40
+ print(f"rel found: b*a^{x}=", b * pow(a, x, n) % n, relation)
41
+ else:
42
+ print(f"rel found: a^{x}=", pow(a, x, n), relation)
43
+ relation.reverse() # the linear algebra is slightly faster if we take the large primes first
44
+ if include_b:
45
+ relation += [ 1, x ]
46
+ else:
47
+ relation += [ 0, x ]
48
+ return relation
49
+
50
+
51
+ # this functions does the linear algebra
52
+ def process_relation(relation: list) -> None or int:
53
+ """Add a new relation to the linear system and keep the system in echelon form."""
54
+ nonlocal a, b, m, n, relations, len_relations, n_relations
55
+
56
+ n_relations += 1
57
+ # Gauss elimination
58
+ for i in range(len_relations):
59
+ ri = relation[i] % m
60
+ if ri == 0:
61
+ continue
62
+ if relations[i] is not None: # subtract the current relations
63
+ relation[i] = 0
64
+ for j in range(i + 1, len_relations + 1):
65
+ relation[j] = (relation[j] - ri * relations[i][j]) % m
66
+ continue
67
+ # normalize the first nonzero entry
68
+ rinv = pow(ri, -1, m)
69
+ relation[i] = 1
70
+ for j in range(i+1, len_relations + 1):
71
+ relation[j] = rinv * relation[j] % m
72
+ relations[i] = relation
73
+ if verbose > 2:
74
+ print(n_relations, f"rel found (index={i}) :", relation)
75
+ elif verbose > 1:
76
+ print(n_relations, f"rel found (index={i})")
77
+ index = i
78
+ break # we don't need a reduced echelon form
79
+ else: # the relation contains no new information
80
+ if verbose > 1:
81
+ print(n_relations,"redundant rel found")
82
+ return None
83
+ #for i in range(index): # reduced echelon form
84
+ # if relations[i] != None:
85
+ # ri = relations[i][index] # make this entry zero
86
+ # if ri > 0:
87
+ # relations[i][index] = 0
88
+ # for j in range(index+1, len_relations + 1):
89
+ # relations[i][j] = (relations[i][j] - ri * relation[j]) % m
90
+ #print(n_relations, f"i={i}={index} ({len_relations})", relations)
91
+ if index == len_relations - 1: # we found the solution
92
+ if verbose:
93
+ print(f"Success after {n_relations} relations out of {len_relations}.")
94
+ #for i in range(lf):
95
+ # p = factorbase[i]
96
+ # print(f'{p:d}',pow(p,m,n)==1,relations[i])
97
+ x = (m - relations[index][len_relations]) % m
98
+ if pow(a, x, n) == b:
99
+ return x
100
+ raise Exception("Sorry, Index Calculus failed! Either the DLP is not solvable, or the order is not prime or incorrect.")
101
+
102
+ #
103
+ # Determine the parameters
104
+ #
105
+ B, expected_trys = determine_factorbound(n)[:2]
106
+ max_trys = 10 * expected_trys
107
+ factorbase = tuple(p for p in sieve_eratosthenes(B) if gcd(p,n) == 1) # compute the factorbse
108
+ factorbase_len = len(factorbase) # length of the factorbase
109
+ if factorbase_len == 0:
110
+ raise Exception("Sorry, Index Calculus could not find a factorbase!")
111
+ smallprimes_len, pollard_k = factorbase_len, None
112
+ if pollard: # should we speed up trial division with Pollard p-1
113
+ smallprimes_len, pollard_k = determine_trialdivison_bounds(B // 150, factorbase)
114
+ if verbose > 0:
115
+ print(f"Factorbase: bound = {B}, size = {factorbase_len}, max_trys = {max_trys}")
116
+
117
+ # Start the work
118
+ n_relations = 0 # number of relations found
119
+
120
+ # first find a relation involving b
121
+ relation = find_relation(True)
122
+
123
+ # Set up the linear system
124
+ len_relations = factorbase_len + 1
125
+ relations = [None] * len_relations
126
+ res = process_relation(relation)
127
+ if res:
128
+ return res
129
+
130
+ while n_relations < 5 * factorbase_len: # find relations for all primes in our factor base
131
+ relation = find_relation(False)
132
+ res = process_relation(relation)
133
+ if res:
134
+ return res
135
+
136
+ raise Exception("Sorry, Index Calculus could not find enough relations! ({n_relations} - {n_relations_redundant} = {n_relations - n_relations_redundant} out of {len_relations})")