Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/RSA-encryption/Intro-Challenges/Challenge-0/encrypt.py
1402 views
1
from Crypto.Util.number import *
2
from Crypto.PublicKey import RSA
3
from secret import flag
4
import gmpy2
5
6
"""
7
pycrypto documentation: https://www.dlitz.net/software/pycrypto/api/2.6/
8
gmpy2 documentation [OPTIONAL]: https://gmpy2.readthedocs.io/en/latest/
9
"""
10
11
# (e, n) together is known as the public key, e is known as the public key exponent, n is known as the modulus
12
# (d, n) together is known as the private key, d is known as the private key exponent, n is known as the modulus
13
14
"""
15
secret values (these are not known to the attacker): d, p, q
16
public values: e, n
17
"""
18
19
# p, q are two primes of size 512 bits
20
# The following pycrypto commands have been used to generate primes of size 512 bits: p = getPrime(512), q = getPrime(512)
21
p = 6958271393287170117448891021448827870244652620796166337874899406278127643022124226656230972235829204217718701711355755622520840943962368410353060326959627L
22
q = 10816988558466468069802205154113557859050665172995721741674476865844313409030354507360669179381457836401919224815040955096510785560864262908230559354811907L
23
24
# n = p*q, n is known as the modulus
25
n = p*q
26
e = 65537
27
28
phin = (p-1)*(q-1)
29
"""
30
Modular inverse c = a^(-1) mod b can be calculated only when GCD(a, b) == 1
31
Hence, the command below checks the same before calculating modular inverse
32
Want to know why we check GCD(a, b) before calculating the modular inverse? You can refer the following links:
33
1. Geeks for Geeks: https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
34
2. Wolfram MathWorld: http://mathworld.wolfram.com/ModularInverse.html
35
3. Wikipedia: https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
36
"""
37
assert GCD(e, phin) == 1
38
# Have a look documentation of gmpy2 and usage of various functions of gmpy2 before moving forward [OPTIONAL]: https://gmpy2.readthedocs.io/en/latest/
39
# Calculating the modular inverse d = e^(-1) mod phin
40
# Note that d is only used for decryption and this script is used to encrypt the message.
41
# The command below is only used to illustrate how d is calculated.
42
d = inverse(e, phin)
43
# You can also use gmpy2's invert(e, phin) to get d
44
45
46
# Transforming a string to a long integer using pycrypto's function bytes_to_long() in Crypto.Util.number
47
# m is the message to be encrypted
48
m = bytes_to_long(flag)
49
50
51
# ciphertext = m^e mod n
52
ciphertext = pow(m, e, n)
53
# converting the ciphertext from long integer to string using long_to_bytes() in Crypto.Util.number
54
ciphertext = long_to_bytes(ciphertext)
55
obj1 = open("ciphertext.txt",'w')
56
obj1.write(ciphertext.encode("hex"))
57