.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "api/gallery/number_theory/modular_arithmetic/plot_02_toy_rsa.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_api_gallery_number_theory_modular_arithmetic_plot_02_toy_rsa.py: A toy RSA encryption/decryption round trip ================================================= RSA's key generation, encryption, and decryption are exactly :func:`~mathematicskit.number_theory.systems.modular_arithmetic.mod_inverse` (to find the private exponent) and :func:`~mathematicskit.number_theory.systems.modular_arithmetic.fast_mod_pow` (to encrypt/decrypt) -- demonstrated here with small (textbook-toy, NOT cryptographically secure) primes. .. GENERATED FROM PYTHON SOURCE LINES 14-16 .. code-block:: Python from mathematicskit.number_theory import euler_totient, fast_mod_pow, mod_inverse .. GENERATED FROM PYTHON SOURCE LINES 17-19 Key generation ----------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 19-29 .. code-block:: Python p, q = 61, 53 # small toy primes (real RSA uses ~1024-bit primes) n = p * q phi_n = euler_totient(n) e = 17 # public exponent, coprime to phi(n) d = mod_inverse(e, phi_n) # private exponent print(f"n = {n}, phi(n) = {phi_n}") print(f"public key: (e={e}, n={n}); private key: (d={d}, n={n})") .. rst-class:: sphx-glr-script-out .. code-block:: none n = 3233, phi(n) = 3120 public key: (e=17, n=3233); private key: (d=2753, n=3233) .. GENERATED FROM PYTHON SOURCE LINES 30-32 Encrypt and decrypt a message ----------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 32-39 .. code-block:: Python message = 65 ciphertext = fast_mod_pow(message, e, n) decrypted = fast_mod_pow(ciphertext, d, n) print(f"message={message} -> ciphertext={ciphertext} -> decrypted={decrypted}") assert decrypted == message .. rst-class:: sphx-glr-script-out .. code-block:: none message=65 -> ciphertext=2790 -> decrypted=65 .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.001 seconds) .. _sphx_glr_download_api_gallery_number_theory_modular_arithmetic_plot_02_toy_rsa.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_02_toy_rsa.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_02_toy_rsa.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_02_toy_rsa.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_