MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / rsafactor

Function rsafactor

ciphers/rsa_factorization.py:19–55  ·  view source on GitHub ↗

This function returns the factors of N, where p*q=N Return: [p, q] We call N the RSA modulus, e the encryption exponent, and d the decryption exponent. The pair (N, e) is the public key. As its name suggests, it is public and is used to encrypt messages. The pair (

(d: int, e: int, n: int)

Source from the content-addressed store, hash-verified

17
18
19def rsafactor(d: int, e: int, n: int) -> list[int]:
20 """
21 This function returns the factors of N, where p*q=N
22
23 Return: [p, q]
24
25 We call N the RSA modulus, e the encryption exponent, and d the decryption exponent.
26 The pair (N, e) is the public key. As its name suggests, it is public and is used to
27 encrypt messages.
28 The pair (N, d) is the secret key or private key and is known only to the recipient
29 of encrypted messages.
30
31 >>> rsafactor(3, 16971, 25777)
32 [149, 173]
33 >>> rsafactor(7331, 11, 27233)
34 [113, 241]
35 >>> rsafactor(4021, 13, 17711)
36 [89, 199]
37 """
38 k = d * e - 1
39 p = 0
40 q = 0
41 while p == 0:
42 g = random.randint(2, n - 1)
43 t = k
44 while True:
45 if t % 2 == 0:
46 t = t // 2
47 x = (g**t) % n
48 y = math.gcd(x - 1, n)
49 if x > 1 and y > 1:
50 p = y
51 q = n // y
52 break # find the correct factors
53 else:
54 break # t is not divisible by 2, break and choose another g
55 return sorted([p, q])
56
57
58if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected