cse week 2
cse week 2
Aim: Implement RSA algorithm to demonstrate the concept of public and private keys
RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that it works on two different
keys i.e. Public Key and Private Key. As the name describes that the Public Key is given to everyone and the Private
key is kept private.
1. A client (for example browser) sends its public key to the server and requests some data.
2. The server encrypts the data using the client’s public key and sends the encrypted data.
Since this is asymmetric, nobody else except the browser can decrypt the data even if a third party has the public key
of the browser.
RSA algorithm uses the following procedure to generate public and private keys:
• Multiply these numbers to find n = p x q, where n is called the modulus for encryption and decryption.
• Choose a number e less than n, such that n is relatively prime to (p - 1) x (q -1). It means that e and (p - 1) x (q
- 1) have no common factor except 1. Choose "e" such that 1<e < φ (n), e is prime to φ (n),
gcd (e,d(n)) =1
• If n = p x q, then the public key is <e, n>. A plaintext message m is encrypted using public key <e, n>. To find
ciphertext from the plain text following formula is used to get ciphertext C.
C = me mod n
Here, m must be less than n. A larger message (>n) is treated as a concatenation of messages, each of which
is encrypted separately.
• To determine the private key, we use the following formula to calculate the d such that:
De mod {(p - 1) x (q - 1)} = 1
Or
De mod φ (n) = 1
• The private key is <d, n>. A ciphertext message c is decrypted using private key <d, n>. To calculate plain text
m from the ciphertext c following formula is used to get plain text m.
m = cd mod n
2. Calculate n = p * q
5. Calculate d using (d * e % t = 1)
# calculating totient, t
t = (p - 1) * (q - 1)
# performing encryption
ct = (message ** e) % n
print(f"Encrypted message is {ct}")
# performing decryption
mes = (ct ** d) % n
print(f"Decrypted message is {mes}")
# Testcase - 1
RSA(p=53, q=59, message=89)
# Testcase - 2
RSA(p=3, q=7, message=12)