50 lines
1.1 KiB
Python
50 lines
1.1 KiB
Python
#!/usr/bin/env python3
|
|
from Cryptotools.Groups.cyclic import Cyclic
|
|
from Cryptotools.Numbers.primeNumber import getPrimeNumber
|
|
from random import randint, choice
|
|
from math import log, log10
|
|
|
|
"""
|
|
Here, we will try to understand why we need to have a generator when we encrypt data for Diffie-Hellman
|
|
https://crypto.stackexchange.com/questions/25489/why-does-diffie-hellman-need-be-a-cyclic-group
|
|
"""
|
|
def operation(a, b, n):
|
|
return (a ** b) % n
|
|
|
|
def getGenerator(gr, p):
|
|
cyclic = Cyclic(gr, p, operation)
|
|
generators = cyclic.getGenerators()
|
|
print(f"All generators: {generators}")
|
|
cyclic.identity()
|
|
print(f"Identity: {cyclic.getIdentity()}")
|
|
|
|
return generators
|
|
|
|
|
|
gr = list()
|
|
# Public value
|
|
p = 13
|
|
g = 0
|
|
for i in range(1, p):
|
|
gr.append(i)
|
|
|
|
print(f"p = {p}")
|
|
print(f"G = {gr}")
|
|
# We try with a generator which is not in list
|
|
generators = getGenerator(gr, p)
|
|
|
|
g = 3 # In the group
|
|
#g = # Not in the group
|
|
#print(f"g = {g}")
|
|
|
|
|
|
|
|
# Try to compute the cyclic subgroup
|
|
for G in range(p + 1):
|
|
res = 0
|
|
for a in range(G):
|
|
r = operation(G, a, p)
|
|
res = res + r
|
|
if res == p:
|
|
print(f"G = {G}; res = {res}")
|