-
Notifications
You must be signed in to change notification settings - Fork 11
/
cge-esm.sage
51 lines (41 loc) · 963 Bytes
/
cge-esm.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
from sage.all import GF
def cge(g: int, x: int, n: int) -> int:
"""
Cyclic Group Exponentiation using "square-and-multiply"
Parameters:
- `g`: generator
- `x`: exponent
- `n`: order
Returns:
- `g^x (mod n)`
"""
ans = 1
base = g
while x > 0:
if x & 1 == 1:
ans = (ans * base) % n # multiply
base = (base * base) % n # square
x >>= 1
return ans
def esm(g: int, x: int, n: int) -> int:
"""
Efficient Scalar Multiplication using "double-and-add"
Parameters:
- `g`: number
- `x`: number
- `n`: order
Returns:
- `g*x (mod n)`
"""
ans = 0
base = g
while x > 0:
if x & 1 == 1:
ans = (ans + base) % n # add
base = (base + base) % n # double
x >>= 1
return ans
if __name__ == "__main__":
F13 = GF(13)
assert F13(4) ^ 7 == cge(4, 7, 13)
assert F13(4) * 7 == esm(4, 7, 13)