From ca4efb2ab8d06f711d4cc2e0dd655c2e1f5d01e2 Mon Sep 17 00:00:00 2001 From: Maxime Vorwerk Date: Thu, 6 Jun 2024 13:03:19 +0200 Subject: [PATCH] Mind your Ps and Qs --- mind_your_ps_and_qs/sol.py | 55 ++++++++++++++++++++++++++++++++++++++ mind_your_ps_and_qs/values | 7 +++++ 2 files changed, 62 insertions(+) create mode 100755 mind_your_ps_and_qs/sol.py create mode 100755 mind_your_ps_and_qs/values diff --git a/mind_your_ps_and_qs/sol.py b/mind_your_ps_and_qs/sol.py new file mode 100755 index 0000000..4f18b61 --- /dev/null +++ b/mind_your_ps_and_qs/sol.py @@ -0,0 +1,55 @@ +#!/usr/bin/python3 +import math + +def totient(p, q): + tot, rem = divmod((p-1) * (q-1), math.gcd(p-1, q-1)) + if rem != 0: + raise Exception("totient calc failed") + return tot + +def egcd(a, b): + x0, x1, y0, y1 = 0, 1, 1, 0 + while a != 0: + (q, a), b = divmod(b, a), a + y0, y1 = y1, y0 - q * y1 + x0, x1 = x1, x0 - q * x1 + return b, x0, x1 + +# https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm +def mod_inv(d, lambda_n): + g, x, _ = egcd(d, lambda_n) + if g != 1: + raise Exception("gcd(d, lambda_n != !") + return x % lambda_n + +def rsa(text, key, n): + return pow(text, key, n) + +with open("values", 'r') as f: + lines = f.readlines() + + C = int(lines[1][3:]) + n = int(lines[2][3:]) + e = int(lines[3][3:]) + p = int(lines[4][3:]) + q = int(lines[5][3:]) + + if p*q == n: + print("factoring correct") + else: + print("factoring incorrect") + + lambda_n = totient(p, q) + + d = mod_inv(e, lambda_n) + #d = pow(d, -1, lambda_n) + + res = rsa(C, d, n) + + text = '' + while (char := (res % 256)) != 0: + text = chr(char) + text; + res >>= 8 + + print(text) + diff --git a/mind_your_ps_and_qs/values b/mind_your_ps_and_qs/values new file mode 100755 index 0000000..2ecd5d8 --- /dev/null +++ b/mind_your_ps_and_qs/values @@ -0,0 +1,7 @@ +Decrypt my super sick RSA: +c: 861270243527190895777142537838333832920579264010533029282104230006461420086153423 +n: 1311097532562595991877980619849724606784164430105441327897358800116889057763413423 +e: 65537 +p: 1955175890537890492055221842734816092141 +q: 670577792467509699665091201633524389157003 +factored using factordb.com