Для RSA:
Я приведу некоторые алгоритмы и коды из моей собственной дипломной работы бакалавра
- p и q, два простых числа
- n = p * q,
n
является частью открытого ключа
e
или public exponent
должны быть взаимно простыми с функцией Эйлера для n
, которая равна (p-1)(q-1)
для простых чисел
Код для поиска публичного показателя:
def find_public_key_exponent(euler_function):
"""
find_public_key_exponent(euler_function)
Finds public key exponent needed for encrypting.
Needs specific number in order to work properly.
:param euler_function: the result of euler function for two primes.
:return: public key exponent, the element of public key.
"""
e = 3
while e <= 65537:
a = euler_function
b = e
while b:
a, b = b, a % b
if a == 1:
return e
else:
e += 2
raise Exception("Cant find e!")
- Далее нам понадобится модульная мультипликативная обратная функция Эйлера (n) и e, что равно
d
, нашему последнему компоненту:
def extended_euclidean_algorithm(a, b):
"""
extended_euclidean_algorithm(a, b)
The result is the largest common divisor for a and b.
:param a: integer number
:param b: integer number
:return: the largest common divisor for a and b
"""
if a == 0:
return b, 0, 1
else:
g, y, x = extended_euclidean_algorithm(b % a, a)
return g, x - (b // a) * y, y
def modular_inverse(e, t):
"""
modular_inverse(e, t)
Counts modular multiplicative inverse for e and t.
:param e: in this case e is a public key exponent
:param t: and t is an Euler function
:return: the result of modular multiplicative inverse for e and t
"""
g, x, y = extended_euclidean_algorithm(e, t)
if g != 1:
raise Exception('Modular inverse does not exist')
else:
return x % t
Открытый ключ: (n, e)
Закрытый ключ: (n, d)
Шифрование: <number> * e mod n = <cryptogram>
Расшифровка: <cryptogram> * d mon n = <number>
Есть еще несколько ограничений, поэтому шифр должен быть безопасным, но он будет работать с условиями, которые я предоставил.
И, конечно же, вам нужно найти способ получить большие простые числа, прочитайте о простое тестирование