toycrypto 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,4 @@
1
+ # SPDX-FileCopyrightText: 2024-present Jeffrey Goldberg <jeffrey@goldmark.org>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ __version__ = "0.1.0"
toy_crypto/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ # SPDX-FileCopyrightText: 2024-present Jeffrey Goldberg <jeffrey@goldmark.org>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ # This __init__.py intentially left blank
toy_crypto/birthday.py ADDED
@@ -0,0 +1,126 @@
1
+ import math
2
+ from . import types
3
+
4
+
5
+ MAX_QBIRTHDAY_P = 1.0 - (10**-8)
6
+ EXACT_THRESHOLD = 1000
7
+
8
+
9
+ def _pbirthday_exact(
10
+ n: types.PositiveInt, classes: types.PositiveInt, coincident: int
11
+ ) -> types.Prob:
12
+ # use notation from Diconis and Mosteller 1969
13
+ c = classes # classes
14
+ k = coincident
15
+
16
+ if k < 2:
17
+ return types.Prob(1.0)
18
+ if k > 2:
19
+ return _pbirthday_approx(n, c, coincident=k)
20
+
21
+ if n >= c:
22
+ return types.Prob(1.0)
23
+
24
+ v_dn = math.perm(c, n)
25
+ v_t = pow(c, n)
26
+
27
+ p = 1.0 - float(v_dn / v_t)
28
+ if not types.is_prob(p):
29
+ raise Exception("this should not happen")
30
+ return p
31
+
32
+
33
+ def _pbirthday_approx(
34
+ n: types.PositiveInt, classes: types.PositiveInt, coincident: int
35
+ ) -> types.Prob:
36
+ # DM1969 notation
37
+ c = classes
38
+ k = coincident
39
+
40
+ if n >= c * (k - 1):
41
+ return types.Prob(1.0)
42
+
43
+ if k < 2:
44
+ return types.Prob(1.0)
45
+
46
+ # p = 1.0 - math.exp(-(n * n) / (2 * d))
47
+
48
+ # lifted from R src/library/stats/R/birthday.R
49
+ LHS = n * math.exp(-n / (c * k)) / (1 - n / (c * (k + 1))) ** (1 / k)
50
+ lxx = k * math.log(LHS) - (k - 1) * math.log(c) - math.lgamma(k + 1)
51
+ p = -math.expm1(-math.exp(lxx))
52
+ if not types.is_prob(p):
53
+ raise Exception("this should not happen")
54
+ return p
55
+
56
+
57
+ def P(
58
+ n: int, classes: int = 365, coincident: int = 2, mode: str = "auto"
59
+ ) -> types.Prob:
60
+ """prob of at least 1 collision among n "people" for c classes".
61
+
62
+ The "exact" method still involves floating point approximations
63
+ and may be very slow for large n.
64
+ """
65
+ c = classes
66
+ k = coincident
67
+
68
+ if not types.is_positive_int(n):
69
+ raise ValueError("n must be a positive integer")
70
+ if not types.is_positive_int(c):
71
+ raise ValueError("classes must be a possible integer")
72
+ if not types.is_positive_int(k):
73
+ raise ValueError("coincident must be a possible integer")
74
+
75
+ if k == 1:
76
+ return types.Prob(1.0)
77
+
78
+ if mode == "auto":
79
+ mode = "exact" if c < EXACT_THRESHOLD else "approximate"
80
+ match mode:
81
+ case "exact":
82
+ return _pbirthday_exact(n, c, coincident=k)
83
+ case "approximate":
84
+ return _pbirthday_approx(n, c, coincident=k)
85
+ case _:
86
+ raise ValueError('mode must be "auto", "exact", or "approximate"')
87
+
88
+
89
+ def Q(prob: float = 0.5, classes: int = 365, coincident: int = 2) -> int:
90
+ """Returns number minimum number n to get a prob of p for c classes"""
91
+
92
+ # Use DM69 notation
93
+ p = prob
94
+ c = classes
95
+ k = coincident
96
+ if not types.is_prob(p):
97
+ raise ValueError(f"p ({p}) must be a probability")
98
+
99
+ if p > MAX_QBIRTHDAY_P:
100
+ raise NotImplementedError(f"Cannot compute for p > {MAX_QBIRTHDAY_P}")
101
+
102
+ # Lifted from R src/library/stats/R/birthday.R
103
+ if p == types.Prob(0):
104
+ return 1
105
+ if math.isclose(p, 1.0):
106
+ return c * (k - 1) + 1
107
+
108
+ # Frist approximation
109
+ # broken down so that I can better understand this.
110
+ term1 = (k - 1) * math.log(c) # log(c^{k-1})
111
+ term2 = math.lgamma(k + 1) # log k!
112
+ term3 = math.log(-math.log1p(-p)) # ?
113
+ log_n = (term1 + term2 + term3) / k # adding log x_i is log prod x_i
114
+ n = math.exp(log_n)
115
+ n = math.ceil(n)
116
+
117
+ if P(n, c, coincident=k) < p:
118
+ n += 1
119
+ while P(n, c, coincident=k) < p:
120
+ n += 1
121
+ elif P(n - 1, c, coincident=k) >= p:
122
+ n -= 1
123
+ while P(n - 1, c, coincident=k) >= p:
124
+ n -= 1
125
+
126
+ return n
toy_crypto/ec.py ADDED
@@ -0,0 +1,353 @@
1
+ """Do not use this!
2
+
3
+ Do not use this. All of this is just to provide a working context
4
+ for the scaler_multiply() method.
5
+
6
+ This is more complicated because I unwisely attempted to make this work both
7
+ for elliptic curves defined over the reals (for the drawings) and for curves
8
+ defined over integer fields.
9
+
10
+ - If you want cryptography in python use https://cryptography.io/en/latest/
11
+
12
+ - If you want to play with elliptic curves in a python-esque environment use SageMath.
13
+
14
+ Do not use the module you are looking at now for anything.
15
+ """
16
+
17
+ import sys
18
+
19
+ if sys.version_info < (3, 11):
20
+ raise Exception("Requires python 3.11")
21
+ from typing import Optional, Self, Any
22
+ from toy_crypto.nt import mod_sqrt
23
+ from toy_crypto.utils import lsb_to_msb
24
+ from toy_crypto.nt import Modulus as Modulus
25
+ from toy_crypto.nt import is_modulus
26
+
27
+
28
+ class Curve:
29
+ """Define a curve of the form y^2 = x^3 + ax + b (mod p)."""
30
+
31
+ def __init__(self, a: int, b: int, p: int) -> None:
32
+ self.p: Modulus = Modulus(p)
33
+ self.a: int = a
34
+ self.b: int = b
35
+
36
+ if self.is_singular():
37
+ raise ValueError(f"{self} is singular")
38
+
39
+ if not is_modulus(self.p):
40
+ raise ValueError("Bad modulus p")
41
+
42
+ self._pai = Point(0, 0, self, is_zero=True)
43
+
44
+ # This assumes (without checking) that the curve has good paramaters
45
+ # and that a generator (base point) has been chosen correctly/
46
+ self._order = (self.p + 1) // 2
47
+
48
+ def is_singular(self) -> bool:
49
+ return (4 * self.a**3 + 27 * self.b * self.b) % self.p == 0
50
+
51
+ @property
52
+ def PAI(self) -> "Point":
53
+ return self._pai
54
+
55
+ @property
56
+ def order(self) -> int:
57
+ return self._order
58
+
59
+ def __repr__(self) -> str:
60
+ # There is probably a nice way to do with with
61
+ # format directives, but I'm not going to dig
62
+ # into those docs now.
63
+ if self.a < 0:
64
+ ax = f"- {-self.a}x"
65
+ else:
66
+ ax = f"+ {self.a}"
67
+
68
+ if self.b < 0:
69
+ b = f"- {-self.b}x"
70
+ else:
71
+ b = f"+ {self.b}"
72
+
73
+ return f"y^2 = x^3 {ax} {b} (mod {self.p})"
74
+
75
+ def compute_y(self, x: int) -> Optional[tuple[int, int]]:
76
+ "Retruns pair of y vaules for x on curve. None otherwise."
77
+ a = self.a
78
+ b = self.b
79
+ p = self.p
80
+ y2: int = (pow(x, 3, p) + ((a * x) % p) + b) % p
81
+ roots = mod_sqrt(y2, p)
82
+ if len(roots) != 2:
83
+ raise ValueError("x is rootless")
84
+
85
+ return roots[0], roots[1]
86
+
87
+ def point(self, x: int, y: int) -> "Point":
88
+ return Point(x, y, self, is_zero=False)
89
+
90
+
91
+ class Point:
92
+ """Point on elliptic curve over the reals"""
93
+
94
+ # I would prefer to have all points belong to a curve
95
+ # but I don't quite get python's classes to do that.
96
+ # as this is all a toy, I'm not going to worry about this now
97
+
98
+ def __init__(
99
+ self, x: int, y: int, curve: Curve, is_zero: bool = False
100
+ ) -> None:
101
+ self.x: int = x
102
+ self.y: int = y
103
+ self.curve: Curve = curve
104
+ self.is_zero: bool = is_zero
105
+
106
+ if not (isinstance(self.x, int) and isinstance(self.y, int)):
107
+ raise TypeError("Points must have integer coordinates")
108
+
109
+ self.x %= self.curve.p
110
+ self.y %= self.curve.p
111
+
112
+ if not self.on_curve():
113
+ raise ValueError("point not on curve")
114
+
115
+ def on_curve(self) -> bool:
116
+ if self.is_zero:
117
+ return True
118
+
119
+ x = int(self.x)
120
+ y = int(self.y)
121
+ a = int(self.curve.a)
122
+ b = int(self.curve.b)
123
+
124
+ p = self.curve.p
125
+ # breaking this down for debugging
126
+ lhs = pow(y, 2, p)
127
+ rhs = (pow(x, 3, p) + a * x + b) % p
128
+
129
+ return lhs == rhs
130
+
131
+ # define P + Q; -P; P += Q; P - Q; P == Q
132
+ def __add__(self, Q: "Point") -> "Point":
133
+ return self.add(Q)
134
+
135
+ def __neg__(self) -> "Point":
136
+ return self.neg()
137
+
138
+ def __iadd__(self, Q: "Point") -> Self:
139
+ return self.iadd(Q)
140
+
141
+ def __sub__(self, Q: "Point") -> "Point":
142
+ return self.__add__(Q.__neg__())
143
+
144
+ def __eq__(self, Q: Any) -> bool:
145
+ if not isinstance(Q, Point):
146
+ return NotImplemented
147
+ if not self and not Q: # both are 0
148
+ return True
149
+ if self.x != Q.x or self.y != Q.y: # x's and y's don't match
150
+ return False
151
+ if self.curve != Q.curve: # They are defined for different curves
152
+ return False
153
+ return True
154
+
155
+ def __bool__(self) -> bool:
156
+ """P is True iff P is not the zero point."""
157
+ return not self.is_zero
158
+
159
+ def __repr__(self) -> str:
160
+ return f"({self.x}, {self.y})"
161
+
162
+ def neg(self) -> "Point":
163
+ """Return additive inverse.
164
+
165
+ :returns: Additive inverse
166
+ :rtype: Point
167
+ """
168
+
169
+ if self.is_zero:
170
+ return self
171
+
172
+ r = self.cp()
173
+ r.y = self.curve.p - r.y
174
+ return r
175
+
176
+ # I don't know how shallow a copy() is in Python, so
177
+ def cp(self) -> "Point":
178
+ """Return a copy of self."""
179
+
180
+ return Point(self.x, self.y, self.curve, is_zero=self.is_zero)
181
+
182
+ def iadd(self, Q: "Point") -> Self:
183
+ """add point to self in place.
184
+
185
+ :param Q: Point to be added
186
+ :type Q: Point
187
+
188
+ :returns: Point
189
+
190
+ :raises TypeError: if Q is not a point
191
+ :raises ValueError if P and Q are not the same subclass of Point
192
+ :raises ValueError: if Q is not on its own curve
193
+ :raises ValueError: if Q is on a distinct curve
194
+ """
195
+
196
+ # The order of checking matters, as each check is seen as
197
+ # as a fall through of prior checks
198
+ if not isinstance(Q, Point):
199
+ return NotImplemented
200
+
201
+ # We don't do curve check on Q if Q is 0
202
+ # P + 0 = P
203
+ if not Q:
204
+ return self
205
+
206
+ # if Q is not on its curve then there is something wrong with it.
207
+ if not Q.on_curve():
208
+ raise ValueError("Point is not on curve")
209
+
210
+ # 0 + Q = Q
211
+ if not self:
212
+ self.x, self.y = Q.x, Q.y
213
+ self.curve = Q.curve
214
+ self.is_zero = Q.is_zero
215
+ return self
216
+
217
+ # if Q is on a different curve, something bad is happening
218
+ if self.curve != Q.curve:
219
+ raise ValueError("Points on different curves")
220
+
221
+ # P + P
222
+ if self == Q:
223
+ return self.idouble()
224
+
225
+ # P + -P = 0
226
+ if self.x == Q.x:
227
+ self.x, self.y = 0, 0
228
+ self.is_zero = True
229
+ return self
230
+
231
+ # Generics would be better than the abuse of type
232
+ # narrowing that I am doing here to call different
233
+ # _addition() methods
234
+
235
+ self.x, self.y = self._nz_addition(Q)
236
+
237
+ return self
238
+
239
+ def add(self, Q: "Point") -> "Point":
240
+ """Add points.
241
+
242
+ :param Q: Point to add
243
+ :type Q: Point
244
+
245
+ :returns: Sum of Q and self
246
+ :rtype: Point
247
+ """
248
+
249
+ r = self.cp()
250
+ r.iadd(Q)
251
+ return r
252
+
253
+ def idouble(self) -> Self:
254
+ if self.is_zero:
255
+ return self
256
+
257
+ xy = self._xy_double()
258
+ if not xy:
259
+ self.x = 0
260
+ self.y = 0
261
+ self.is_zero = True
262
+ else:
263
+ self.x, self.y = xy
264
+
265
+ return self
266
+
267
+ def double(self) -> "Point":
268
+ if self.is_zero:
269
+ return self.cp()
270
+
271
+ P = self.cp()
272
+ P = P.idouble()
273
+
274
+ return P
275
+
276
+ def _xy_double(self) -> Optional[tuple[int, int]]:
277
+ """(x, y) for x, y of doubled point. None if point at infinity
278
+
279
+ :returns: new coordinates, x and y
280
+ :rtype: Optional[tuple[int,int]]
281
+
282
+
283
+ This does _some_ validity check of input values,
284
+ but it might just return erroneous results the following
285
+ conditions aren't met
286
+ - self.curve.p is prime
287
+ - self.curve is well defined
288
+ - self.x, self.y are integers
289
+ - self is on the curve
290
+ - self is not the point at infinity
291
+ """
292
+
293
+ if self.is_zero:
294
+ return None
295
+
296
+ if self.y == 0:
297
+ return None
298
+
299
+ m = self.curve.p
300
+ top = ((3 * (self.x * self.x)) % m + self.curve.a) % m
301
+ bottom = (2 * self.y) % m
302
+ inv_bottom = pow(bottom, m - 2, m)
303
+ s = top * inv_bottom % m
304
+
305
+ x = (pow(s, 2, m) - 2 * self.x) % m
306
+ y = (s * (self.x - x) - self.y) % m
307
+
308
+ return (x, y)
309
+
310
+ def scaler_multiply(self, n: int) -> "Point":
311
+ """returns n * self"""
312
+
313
+ n = n % self.curve.order
314
+ sum = self.curve.PAI.cp() # additive identity
315
+ doubled = self
316
+ for bit in lsb_to_msb(n):
317
+ if bit == 1:
318
+ sum += doubled
319
+ doubled = doubled.double() # toil and trouble
320
+ return sum
321
+
322
+ def _nz_addition(self, Q: "Point") -> tuple[int, int]:
323
+ """returns x, y over finite field Z_p"""
324
+
325
+ if self.is_zero or Q.is_zero:
326
+ raise ValueError("this is for non-zero points only")
327
+
328
+ m = self.curve.p # have the modulus handy
329
+
330
+ # The following breaks up the point addition math into
331
+ # gory details and steps. This helped in debugging.
332
+
333
+ # s = (Q.y - self.y) / (Q.x - self.x)
334
+ # = top/bot
335
+ # = top * inv_bot
336
+ #
337
+ # And we do our mod p reductions at every opportunity
338
+ bottom = Q.x - self.x
339
+ # because p is prime, we can use a^{p-2} % p to compute inverse of a
340
+ inv_bot = pow(bottom, m - 2, m)
341
+ top = (Q.y - self.y) % m
342
+ s = top * inv_bot % m
343
+ s2 = (s * s) % m
344
+
345
+ # x = (s^2 - Px) - Qx
346
+ x = (s2 - self.x) - Q.x
347
+ x %= m
348
+
349
+ # y = s(Px - x) - Qy
350
+ y = s * (self.x - x) - self.y
351
+ y %= m
352
+
353
+ return x, y