diff --git a/.gitignore b/.gitignore index e01c701ffa27706cb2fea57ea2f3916660d798c3..0a6f7338b5d5dd870204ca3cc4959765b8152bcf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # --- casual --- .vscode +__pycache__ # --- LaTeX --- main.aux diff --git a/__pycache__/algo.cpython-38.pyc b/__pycache__/algo.cpython-38.pyc index 1dfd418ed079c6daf1e86523cb9e4f2f47863f1b..07a9f1198c7089b743e047fd6a3e1b92d1a4ceee 100644 Binary files a/__pycache__/algo.cpython-38.pyc and b/__pycache__/algo.cpython-38.pyc differ diff --git a/algo.py b/algo.py index 8e292942931104370a388648b0a45ba5ee5c856e..1b76bd8ee5cf305339fdbe8d5907300fd61cf88b 100644 --- a/algo.py +++ b/algo.py @@ -56,7 +56,7 @@ def exponentiation_rapide(a, exp, n): n (uint): the modulo Returns: - uint: An array with the pgdc and the coefficients of bachet_bezout, [pgdc, u, v] + uint: The result of of the quick explanation """ if (a == 0): @@ -72,11 +72,11 @@ def exponentiation_rapide(a, exp, n): b = (b**2) % n exp = exp // 2 - return r + return int(r) def is_square(a): - """Check if a number is a perfect square, using the Newton methode - from https://stackoverflow.com/questions/2489435/check-if-a-number-is-a-perfect-square + """Check if a number is a perfect square, based on the "Babylonian algorithm" for square root, + from : https://stackoverflow.com/questions/2489435/check-if-a-number-is-a-perfect-square Args: a (uint): number checked @@ -85,7 +85,7 @@ def is_square(a): bool: true if the number is a perfect square, otherwise flase """ - x = a // 2 + x = a // 2 # start value seen = set([x]) while x * x != a: @@ -109,15 +109,32 @@ def fermat_factorization(n): tuple of uint: the two coeficient a and b """ - a = math.ceil(math.sqrt(n)) - b = 0 - while(True): - b2 = a**2 - n - - if (is_square(b2)): - b = math.sqrt(b2) - break - + if (n % 2 == 0): + print("Fermat's factorization don't work on even number") + return + + a = math.ceil(math.sqrt(n)) # a = 26262277040 (for the key given) + b2 = a**2 - n + + while (not is_square(b2)): a += 1 + b2 = a**2 - n + + if (a >= n): + print("Warning : n could be prime !") + b = int(math.sqrt(b2)) return (a, b) + +def decode_msg(M): + """Decode a code UTF-8 in characters + from : Niklaus Eggenberg + + Args: + M (uint): code UTF-8 + + Returns: + strings: a strings containing characters UTF-8 + """ + + return M.to_bytes((M.bit_length() + 7) // 8, "little").decode("utf-8") diff --git a/main.py b/main.py index 3d63c9d7844df077381f9046f8a9f9b588a7d7fd..a2927fb28f063bc12be37fe570348268b959fdd9 100644 --- a/main.py +++ b/main.py @@ -1,57 +1,52 @@ from algo import * def main(): - mu = { - 416687707, - 420774592, - 1078076801, - 372477309, - 1915438026, - 306996859, - 1858268340, - 1934595642, - 444729462, - 1953792398, - 1118037789, - 1220832721, - 701508709, - 1976470330, - 1081245832, - 1480954262, - 921801986, - 1154526486, - 1974597168, - 812527863, - 1895548977, - 1274512749, - 712992858 - } #encrypted message - n = 1989929159 #first element public key - e = 2203 #second element public key + mu = [ + 31726849986005826981, + 305966565717393601613, + 61497322861823383198, + 269645690420162032117, + 155457162093765938384, + 24931468152962121635, + 138444967690527010216, + 282789589899417404817, + 134251529920691060404, + 423054566352157178418, + 265453042944217161627, + 39119050384849643825 + ] # encrypted message + n = 455649012989940178621 # first element public key + e = 5303 # second element public key length = len(mu) # --- private element --- - M = [] #decriypted message - msg = "" #message (string) - p = 0 #primes numbers - q = 0 - d = 0 #private key + M = [] # decriypted message + msg = "" # message (string) + p = 0 # fisrt prime number + q = 0 # second prime number + d = 0 # private key #--- crack RSA --- a, b = fermat_factorization(n) - + p = a + b q = a - b - - print(n == p * q, "\n") - + fi = (p - 1) * (q - 1) - d = inverse_modulaire(e, fi) + d = inverse_modulaire(e, fi) # get private key # --- decode mu & initialise msg --- for i in range(length): - M[i] = exponentiation_rapide(mu[i], d, n) + M.append(exponentiation_rapide(mu[i], d, n)) + + for m in M: + msg += decode_msg(m) + # --- output --- + print("p :", p, "\nq :", q, "\nfi :", fi, "\nd :", d, "\nmsg :", msg) + + if __name__ == "__main__": - main() \ No newline at end of file + main() + \ No newline at end of file diff --git a/main.tex b/main.tex index d61e586b7721daa99d59aeed4a32dff62f8b6170..78c85b8d5898d0251e45867b74c52f3ae43afcd8 100644 --- a/main.tex +++ b/main.tex @@ -64,8 +64,7 @@ bmargin=1.25in]{geometry} % --- Variables --- -\def \mytitle{blablabla} -\def \mysubtitle{blablabla} +\def \mytitle{Rapport travail pratique RSA} \def \myauthor{Adrian \textsc{Spycher}, Flavio \textsc{Morrone} \& Jad \textsc{Tayan}} \def \myuniversity{\href{https://www.hesge.ch/hepia/}{HEPIA}} \def \mydepartment{\href{https://www.hesge.ch/hepia/bachelor/informatique-et-systemes-communication}{Informatique et systemes communication}} @@ -157,15 +156,11 @@ bmargin=1.25in]{geometry} \vspace{0.5cm} - \mysubtitle - - \vspace{1.5cm} - \myauthor \vfill - \includegraphics[width=0.5\textwidth]{cryptography.jpg} + \includegraphics[width=0.75\textwidth]{cryptography.jpg} \vfill @@ -206,96 +201,131 @@ bmargin=1.25in]{geometry} \chapter{Introduction} \label{cha:Introduction} +% Ecrivez une brève introduction sur le contexte du TP. Soyez créatifs pour mentionner les +% fondements théoriques du cours sans pour autant copier les slides ! -% --- Section 1.1 : Contexte du travail --- -\section{Contexte du travail} -\label{sec:Contexte du travail} +\newpage -blablabla -% --- Section 1.2 : Plan --- +%---------------------------------------------------------------------------------------- +% MÉTHODOLOGIE +%---------------------------------------------------------------------------------------- -\section{Plan} -\label{sec:Plan} +\chapter{Méthodologie} +\label{cha:Méthodologie} -blablabla -\vspace*{0.25cm} -\begin{remark} - blablabla \href{https://malaspinas.academy/phys/planets/enonce.html}{malaspinas.academy} -\end{remark} +% --- Section 2.1 : Description du problème --- +\section{Description du problème} +\label{sec:Description du problème} -\newpage +% Briève description du problème +% --- Section 2.2 : Méthode de résolution --- -%---------------------------------------------------------------------------------------- -% CHAPTER NAME -%---------------------------------------------------------------------------------------- +\section{Méthode de résolution} +\label{sec:Méthode de résolution} -\chapter{Chapter name} -\label{cha:Chapter name} +% Rappelez-vous que vous devez convaincre vos supérieurs que votre méthode est la bonne, +% mais que, comme tout bon supérieur qui se doit, il ne comprendra pas les détails, mais +% aimera entendre le nom de vos informateurs et vos sources! +% Pensez à TOUJOURS justifier vos propos. Vos supérieurs sont très à cheval là-dessus. Evitez les « on +% sait que », « on montre que », les relatifs vagues du genre « très long » ou « trop long » ou encore +% les conclusions sans fondement du type « A est plus complexe que B ». Posez-vous toujours la +% question « pourquoi est-ce le cas » et, si la réponse n'est pas triviale, expliquez (parfois, 3 mots +% suffisent !). -% --- Section 2.1 : Description du problème --- +% TODO : add bibliogrpahy +Pour pouvoir cracker cette clefs RSA, nous avons utilisé la méthode de la factorisation de Fermat. +C'est un algorithme de décomposition en produit de facteurs premiers d'un entier naturel, autrement dit, il va nous aider à retrouver $p$ et $q$ qui composent $n$. -\section{Description du problème} -\label{sec:Description du problème} +Cette algorithme dit que tout entier naturel impair $n$ se décompose en la différence de deux carrés qui peuvent être ensuite factorisé, on obtient : +\[ + n = a^2 - b^2 = (a + b)(a - b) = p \cdot q +\] -blablabla -\begin{itemize} - \item bla - \item bla - \item bla -\end{itemize} +Dans notre cas, on assicie la valeur de $p$ à $a + b$ et la valeur de $q$ à $a - b$. +Si $p$ et $q$ sont tout deux différents de 1, alors ce sont des facteurs non triviaux de $n$. +Autrement, on se retrouverait avec $n = n \cdot 1$, qui signifirait que $n$ est premier. + +Algébriquement, on voit que +\[ + b^2 = a^2 - n +\] -% --- Section 2.2 : Bagage mathématique --- +Sachant que $a$ et $b$ sont deux nombre entier, on cherche une valeur de $a$ qui vérifie que $b^2$ ait une racine entière. +Le point de départ de $a$ serra $\ \sqrt[]{n} \ $ arrondis au supérieur, car en-dessous, $b^2$ serait inférieur ou égale à 0, ce qui est impossible. -\section{Bagage mathématique} -\label{sec:Bagage mathématique} +\newpage % prettier -blabla +L'algorithme que nous avons fait se présente alors sous cette forme : -% - Sub-section 2.2.1 : Les lois de Newton - +\begin{figure*}[!h] + \centering -\subsection*{Les lois de Newton} -\label{sub:Les lois de Newton} + \begin{subfigure}{.5\linewidth} -blabla + \begin{algorithmic} + \setstretch{1.3} -% --- Section 2.3 : Structure du code --- + \Procedure{Fermat factorization}{$n$} -\section{Structure du code} -\label{sec:Structure du code} + \State $a \gets $ ceil($\ \sqrt[]{n} \ $) + \State $\text{b2} \gets a^2 - n$ -blablabla + \While {b2 is not square} -\begin{figure}[h] - \centering + \State $a \gets a + 1$ + \State $\text{b2} \gets a^2 - n$ - \begin{subfigure}{.6\linewidth} - \centering + \EndWhile - %\includegraphics[width=.8\textwidth]{struct_planet.png} - \caption{Structure planète} - \end{subfigure} + \State $b \gets \sqrt[]{\text{b2}}$ + \State \Return $a, b$ - \vspace*{1cm} + \EndProcedure - \begin{subfigure}{.6\linewidth} - \centering + \end{algorithmic} - %\includegraphics[width=.8\textwidth]{struct_system.png} - \caption{Structure système} \end{subfigure} +\end{figure*} - \caption{Les deux principales structures du code} - \label{fig:DeuxPrincipalesStrucutres} -\end{figure} +% TODO : add bibliogrpahy +Pour savoir si $b^2$ avait une racine entière, nous avons utilisé une méthode que nous avons retrouver sur \textit{StackOverflow} qui est basé sur l'algorithme Babyloniens. +Qui, en passant les détails, parcours différentes valeurs possibles calculé par rapport au nombre donnée. +Si les valeurs testé ne sont pas la racine, c'est que la racine n'est pas entière. + +Après avoir récupérer $p$ et $q$, nous pouvons retrouver la clef privée $d$, notamment, en calculant la valeur de $\phi$ : +\[ + \phi = (p - 1) \cdot (q - 1) +\]\[ + d = \text{l'inverse modulaire de } \phi \text{ de } e +\] + +On peut maintenant alors décodé le message en clair $M$ en utilisant l'exponentiation rapide de sur le message chiffré $\mu$. +\[ + M \equiv_n \: \mu^d +\] + +Et c'est comme ça que nous avons déchiffré le message. + + +% --- Section 2.3 : Application --- + +\section{Application} +\label{sec:Application} + +% Sans pour autant fournir votre code ni une documentation de ce dernier (le boss n'est pas +% programmeur !), décrivez votre approche dans les grandes lignes. Privilégiez le « Pourquoi cela +% fonctionne » plutôt que le « comment l'avons-nous codé ». Mentionnez également les éventuelles +% astuces d'implémentation non triviales ou les bugs rencontrés, qui assureront aux prochains agents +% de ne pas reproduire les mêmes erreurs ! \newpage @@ -310,64 +340,41 @@ blablabla \label{cha:Résultats} -blablabla +% N'oubliez pas de présenter votre résultat final et convainquez vos dirigeants de votre performance +% hors normes. Expliquez pourquoi vous avez réussi à craquer un code que la théorie dit devoir +% prendre des milliards d'années, et comment votre propre gouvernement devrait s'y prendre pour +% protéger ses messages ! -\begin{figure}[!h] - \centering - % \includegraphics[width=.41\textwidth]{Fig2_B612_Kry.png} - \caption{Capture d'écran de la simulation avec des planètes fictives} - \label{fig:SimulationPlanètesFictives} -\end{figure} +\newpage -blablabla -\begin{table}[h] - \centering - \rowsep{1.3} - \colsep{10pt} - - \begin{tabular}{lllll} - \toprule - \thead{Planète} & \thead{Masse} & \thead{Demi-grand axe} & \thead{Excentricité} & \thead{Périhélie} \\ - \midrule - Mercure & $ 3.3011 \cdot 10^{23} $ & $ 5.790905 \cdot 10^{10} $ & $ 2.05 \cdot 10^{-1} $ & $ 4.60012 \cdot 10^{10} $ \\ - Venus & $ 4.8675 \cdot 10^{24} $ & $ 1.082095 \cdot 10^{11} $ & $ 6.78 \cdot 10^{-3} $ & $ 1.07476 \cdot 10^{11} $ \\ - Terre & $ 5.9736 \cdot 10^{24} $ & $ 1.495978 \cdot 10^{11} $ & $ 1.671 \cdot 10^{-2} $ & $ 1.47098 \cdot 10^{11} $ \\ - Mars & $ 6.4185 \cdot 10^{23} $ & $ 2.27944 \cdot 10^{11} $ & $ 9.339 \cdot 10^{-2} $ & $ 2.06655 \cdot 10^{11} $ \\ - Jupiter & $ 1.8986 \cdot 10^{27} $ & $ 7.7834 \cdot 10^{11} $ & $ 4.839 \cdot 10^{-2} $ & $ 7.4068 \cdot 10^{11} $ \\ - Saturne & $ 5.6846 \cdot 10^{26} $ & $ 1.4267 \cdot 10^{12} $ & $ 5.39 \cdot 10^{-2} $ & $ 1.3498 \cdot 10^{12} $ \\ - Uranus & $ 8.6810 \cdot 10^{25} $ & $ 2.8707 \cdot 10^{12} $ & $ 4.726 \cdot 10^{-2} $ & $ 2.735 \cdot 10^{12} $ \\ - Neptune & $ 1.0243 \cdot 10^{26} $ & $ 4.4984 \cdot 10^{12} $ & $ 8.59 \cdot 10^{-3} $ & $ 4.4598 \cdot 10^{12} $ \\ - B612 & $ 1.8986 \cdot 10^{20} $ & $ 3.7834 \cdot 10^{11} $ & $ 2.4195 \cdot 10^{-1} $ & $ 3.4068 \cdot 10^{11} $ \\ - Krypton & $ 5.6846 \cdot 10^{26} $ & $ 6.4267 \cdot 10^{11} $ & $ 5.39 \cdot 10^{-2} $ & $ 6.3498 \cdot 10^{11} $ \\ - \bottomrule - \end{tabular} - - \caption{Paramètres des planètes utilisés} - \label{tab:Paramètres des planètes utilisés} -\end{table} - -blablabla -\[ - v_p(0) = \sqrt{ \frac{G \cdot M \cdot (1 + e_p)}{a_p \cdot (1 - e_p)}} \cdot \frac{\vec{r}_p}{||\vec{r}_p||} -\] +%---------------------------------------------------------------------------------------- +% CONCLUSION +%---------------------------------------------------------------------------------------- + +\chapter{Conclusion} +\label{cha:Conclusion} + +% faire une brève conclusion \newpage %---------------------------------------------------------------------------------------- -% CONCLUSION +% BIBLIOGRAPHIE %---------------------------------------------------------------------------------------- -\chapter{Conclusion} -\label{cha:Conclusion} +\chapter*{Bibliographie} +\addcontentsline{toc}{chapter}{Bibliographie} + +% \bibliographystyle{plain} +% \bibliography{bibliography.bib} -blablabla \newpage