kryptografia/1/2.py

30 lines
786 B
Python

from gmpy2 import mpz
def extended_gcd(a, b):
if b == 0:
return (a, mpz(1), mpz(0))
else:
gcd, x1, y1 = extended_gcd(b, a % b)
x = y1
y = x1 - (a // b) * y1
return (gcd, x, y)
def modinv(b, n):
gcd, x, y = extended_gcd(b, n)
if gcd != 1:
raise ValueError(f"Odwrotność modulo nie istnieje, ponieważ gcd({b}, {n}) = {gcd} ≠ 1.")
else:
return x % n
n = mpz(input("Podaj n: "))
b = mpz(input("Podaj b: "))
try:
inverse = modinv(b, n)
print(f"Odwrotność {b} modulo {n} to {inverse}.")
if (b * inverse) % n == 1:
print(f"Sprawdzenie: ({b} * {inverse}) mod {n} = 1\n")
else:
print("Błąd w obliczeniach.\n")
except ValueError as e:
print(f"Dla b = {b}, n = {n}: {e}\n")