Path: blob/master/RSA-encryption/Intro-Challenges/Challenge-0/encrypt.py
1402 views
from Crypto.Util.number import *1from Crypto.PublicKey import RSA2from secret import flag3import gmpy245"""6pycrypto documentation: https://www.dlitz.net/software/pycrypto/api/2.6/7gmpy2 documentation [OPTIONAL]: https://gmpy2.readthedocs.io/en/latest/8"""910# (e, n) together is known as the public key, e is known as the public key exponent, n is known as the modulus11# (d, n) together is known as the private key, d is known as the private key exponent, n is known as the modulus1213"""14secret values (these are not known to the attacker): d, p, q15public values: e, n16"""1718# p, q are two primes of size 512 bits19# The following pycrypto commands have been used to generate primes of size 512 bits: p = getPrime(512), q = getPrime(512)20p = 6958271393287170117448891021448827870244652620796166337874899406278127643022124226656230972235829204217718701711355755622520840943962368410353060326959627L21q = 10816988558466468069802205154113557859050665172995721741674476865844313409030354507360669179381457836401919224815040955096510785560864262908230559354811907L2223# n = p*q, n is known as the modulus24n = p*q25e = 655372627phin = (p-1)*(q-1)28"""29Modular inverse c = a^(-1) mod b can be calculated only when GCD(a, b) == 130Hence, the command below checks the same before calculating modular inverse31Want to know why we check GCD(a, b) before calculating the modular inverse? You can refer the following links:321. Geeks for Geeks: https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/332. Wolfram MathWorld: http://mathworld.wolfram.com/ModularInverse.html343. Wikipedia: https://en.wikipedia.org/wiki/Modular_multiplicative_inverse35"""36assert GCD(e, phin) == 137# Have a look documentation of gmpy2 and usage of various functions of gmpy2 before moving forward [OPTIONAL]: https://gmpy2.readthedocs.io/en/latest/38# Calculating the modular inverse d = e^(-1) mod phin39# Note that d is only used for decryption and this script is used to encrypt the message.40# The command below is only used to illustrate how d is calculated.41d = inverse(e, phin)42# You can also use gmpy2's invert(e, phin) to get d434445# Transforming a string to a long integer using pycrypto's function bytes_to_long() in Crypto.Util.number46# m is the message to be encrypted47m = bytes_to_long(flag)484950# ciphertext = m^e mod n51ciphertext = pow(m, e, n)52# converting the ciphertext from long integer to string using long_to_bytes() in Crypto.Util.number53ciphertext = long_to_bytes(ciphertext)54obj1 = open("ciphertext.txt",'w')55obj1.write(ciphertext.encode("hex"))5657