0% found this document useful (0 votes)
8 views8 pages

RSA Public-Key Cryptosystem Implementation

The document outlines an experiment on implementing the RSA public-key cryptosystem, focusing on key generation, encryption, and decryption processes. It explains the mathematical principles behind RSA, including the importance of prime numbers and modular arithmetic for security. The experiment concludes that the security of RSA relies on the difficulty of factoring large prime numbers.

Uploaded by

pranayfadtare7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

RSA Public-Key Cryptosystem Implementation

The document outlines an experiment on implementing the RSA public-key cryptosystem, focusing on key generation, encryption, and decryption processes. It explains the mathematical principles behind RSA, including the importance of prime numbers and modular arithmetic for security. The experiment concludes that the security of RSA relies on the difficulty of factoring large prime numbers.

Uploaded by

pranayfadtare7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BHARATIYA VIDYA BHAVAN’S

SARDAR PATEL INSTITUTE OF TECHNOLOGY


Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India

DEPARTMENT OF COMPUTER ENGINEERING


SUBJECT: Cryptography and System Security

Name Pranay Anil Fadtare

UID 2022300026

BATCH B

EXP NO. 3

Aim: To implement the RSA public-key cryptosystem for:


● Key generation (creating public and private keys)
● Encryption of a message using the public key
● Decryption of a message using the private key

Problem Definition:
● To implement the RSA (Rivest-Shamir-Adleman) asymmetric cryptographic algorithm.
● To understand the mathematical principles behind public-key cryptography, including the use of
prime numbers and modular arithmetic.
● To develop a program that can generate a valid public-private key pair based on a given bit
length.
● To observe how a plaintext message is converted into a numerical format for encryption and back
into text after decryption.
● To analyze how the security of the RSA algorithm relies on the computational difficulty of
factoring large prime numbers.

Theory:
Asymmetric Cryptography, also known as Public-Key Cryptography, is a cryptographic system that uses
pairs of keys. Each pair consists of a public key, which can be shared with anyone, and a private key,
which must be kept secret. Data encrypted with the public key can only be decrypted with the
corresponding private key.
The RSA (Rivest-Shamir-Adleman) algorithm is the most widely used public-key cryptosystem. Its
security is based on the practical difficulty of the integer factorization problem: while it is easy to
multiply two large prime numbers, it is computationally infeasible to factor their product back into the
original primes.

The RSA algorithm involves three main stages: key generation, encryption, and decryption.
1. Key Generation
The process of creating the public and private keys follows these steps:
● Choose two large and distinct prime numbers, p and q. The security of the keys depends on the
size of these primes.
● Compute the modulus n, which is the product of the primes: n = p * q. This value n is used for
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India

DEPARTMENT OF COMPUTER ENGINEERING


SUBJECT: Cryptography and System Security
both the public and private keys.
● Compute Euler's Totient Function, φ(n) = (p - 1) * (q - 1). This value represents the number of
positive integers less than n that are relatively prime to n. It must be kept secret.
● Choose a public exponent e such that 1 < e < φ(n) and e is coprime to φ(n) (i.e., gcd(e, φ(n)) =
1). A common choice for e is 65537. The public key is the pair (e, n).
● Compute the private exponent d as the modular multiplicative inverse of e modulo φ(n). This is
expressed as d ≡ e⁻¹ (mod φ(n)). The private key is the pair (d, n).

2. Encryption
To encrypt a plaintext message m, it must first be converted into an integer where 0 ≤ m < n. The
encryption is then performed using the recipient's public key (e, n):

c ≡ m^e mod n

The resulting integer c is the ciphertext.

3. Decryption
To decrypt the ciphertext c, the recipient uses their own private key (d, n):

m ≡ c^d mod n

This calculation reverses the encryption process and recovers the original message integer m, which can
then be converted back into text. The mathematical relationship between e, d, and φ(n) ensures that this
process works correctly.

Observations:
1. Asymmetric Process: The core of the algorithm is its asymmetric nature. A message encrypted
with the public key can only be decrypted by its corresponding private key. This one-way
relationship is fundamental to how it provides security.
2. Importance of Key Size: The security of RSA is directly tied to the bit length of the modulus n.
A larger key size exponentially increases the difficulty of factoring n back into its original primes
(p and q), thus making the encryption stronger against brute-force attacks.
3. Numerical Operations: RSA is a purely mathematical cipher. This means that any plaintext,
such as a string of text, must first be converted into a numerical representation before encryption
can occur. The resulting ciphertext is also a number, which must be converted back to text after
decryption.
4. Key Components: The generated keys consist of a public exponent (e), a private exponent (d),
and a shared modulus (n). While e is often a small, standard number for efficiency, the private
exponent d is a very large number derived from the prime factors of n, making it computationally
infeasible to guess without knowing those factors.
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India

DEPARTMENT OF COMPUTER ENGINEERING


SUBJECT: Cryptography and System Security

Code:
import [Link]
import math
import sys

[Link](2000)

def gcd(a, b):


return [Link](a, b)

def mod_inverse(e, phi):


try:
return pow(e, -1, phi)
except ValueError:
return None

def generate_keys(bit_length):
p = [Link](bit_length // 2)
q = [Link](bit_length // 2)

while p == q:
q = [Link](bit_length // 2)
n = p * q
phi = (p - 1) * (q - 1)

e = 65537
while gcd(e, phi) != 1:
p = [Link](bit_length // 2)
q = [Link](bit_length // 2)
while p == q:
q = [Link](bit_length // 2)
n = p * q
phi = (p - 1) * (q - 1)

d = mod_inverse(e, phi)

public_key = (e, n)
private_key = (d, n)

return public_key, private_key

def encrypt(public_key, plaintext):


"""
Encrypts a plaintext message using the public key.
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India

DEPARTMENT OF COMPUTER ENGINEERING


SUBJECT: Cryptography and System Security
c = m^e mod n
"""
e, n = public_key
try:
m = int.from_bytes([Link]('utf-8'), 'big')
except AttributeError:
m = int([Link]('utf-8').hex(), 16)

if m >= n:
raise ValueError("Message is too large for the given key size. Please use a larger
key or smaller message.")

ciphertext = pow(m, e, n)
return ciphertext

def decrypt(private_key, ciphertext):


"""
Decrypts a ciphertext message using the private key.
m = c^d mod n
"""
d, n = private_ke
m = pow(ciphertext, d, n)
try:
plaintext = m.to_bytes((m.bit_length() + 7) // 8, 'big').decode('utf-8')
except AttributeError:
byte_string = '%x' % m
if len(byte_string) % 2:
byte_string = '0' + byte_string
plaintext = [Link](byte_string).decode('utf-8')

return plaintext

def main():
print("RSA Public-Key Cryptosystem Implementation")
public_key = None
private_key = None

while True:
print("\n" + "="*40)
print("Menu:")
print("1. Generate RSA Keys")
print("2. Encrypt a message")
print("3. Decrypt a message")
print("4. Quit")
print("="*40)
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India

DEPARTMENT OF COMPUTER ENGINEERING


SUBJECT: Cryptography and System Security
choice = input("Enter your choice (1-4): ")

if choice == '1':
try:
bit_length = int(input("Enter desired key bit-length (e.g., 512, 1024): "))
if bit_length < 256:
print("Bit length is too small. Please choose a larger value (e.g.,
512).")
continue
public_key, private_key = generate_keys(bit_length)
print("\nKeys generated successfully!")
print(f"Public Key (e, n):\n e = {public_key[0]}\n n = {public_key[1]}\n")
print(f"Private Key (d, n):\n d = {private_key[0]}\n n = {private_key[1]}\n")
except ValueError:
print("Invalid input. Please enter a valid integer for bit-length.")

elif choice == '2':


plaintext = input("Enter the message to encrypt: ")

use_generated = 'n'
if public_key:
use_generated = input("Use the keys generated in this session? (y/n):
").lower()

if use_generated == 'y':
pk_to_use = public_key
else:
try:
e_in = int(input("Enter public key exponent (e): "))
n_in = int(input("Enter public key modulus (n): "))
pk_to_use = (e_in, n_in)
except ValueError:
print("Invalid key components. Please enter integers.")
continue

try:
ciphertext = encrypt(pk_to_use, plaintext)
print(f"\nEncrypted Ciphertext:\n{ciphertext}")
except ValueError as e:
print(f"Encryption Error: {e}")

elif choice == '3':


try:
ciphertext = int(input("Enter the ciphertext to decrypt (as a number): "))
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India

DEPARTMENT OF COMPUTER ENGINEERING


SUBJECT: Cryptography and System Security
use_generated = 'n'
if private_key:
use_generated = input("Use the keys generated in this session? (y/n):
").lower()

if use_generated == 'y':
sk_to_use = private_key
else:
try:
d_in = int(input("Enter private key exponent (d): "))
n_in = int(input("Enter private key modulus (n): "))
sk_to_use = (d_in, n_in)
except ValueError:
print("Invalid key components. Please enter integers.")
continue

decrypted_message = decrypt(sk_to_use, ciphertext)


print(f"\nDecrypted Plaintext:\n{decrypted_message}")

except ValueError:
print("Invalid ciphertext. Please enter a valid integer.")
except Exception as e:
print(f"An error occurred during decryption: {e}")

elif choice == '4':


print("Quitting the program.")
break

else:
print("Invalid choice. Please enter a number between 1 and 4.")

if name == " main ":


main()

Output:
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India

DEPARTMENT OF COMPUTER ENGINEERING


SUBJECT: Cryptography and System Security

Conclusion: In this experiment, I successfully implemented the RSA public-key cryptosystem, covering
key generation, encryption, and decryption. I learned how asymmetric cryptography works by using a
distinct public key to encrypt a message and a secret private key to decrypt it, ensuring that only the
intended recipient can read the message. The experiment demonstrated that the security of this system
relies fundamentally on the mathematical difficulty of factoring large prime numbers.
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India

DEPARTMENT OF COMPUTER ENGINEERING


SUBJECT: Cryptography and System Security

Common questions

Powered by AI

To encrypt a message using RSA, the plaintext message is first converted into an integer m that satisfies 0 ≤ m < n, where n is the modulus from the recipient's public key (e, n). The ciphertext c is then computed as c ≡ m^e mod n, using the public exponent e. To decrypt, the recipient applies their private key (d, n) to calculate m ≡ c^d mod n, recovering the original message integer. This step relies on the mathematical property inherent in the RSA algorithm, where the modular exponentiation using the correct d reverses the encryption, rendering the original plaintext .

Key generation in the RSA algorithm involves choosing two large distinct prime numbers, p and q, and computing their product n, which serves as the modulus for both the public and private keys. Euler's Totient Function, φ(n), is calculated as (p - 1)(q - 1), representing the number of integers less than n that are coprime to n, and it is kept secret. A public exponent e is chosen such that 1 < e < φ(n) and gcd(e, φ(n)) = 1, ensuring it's coprime to φ(n). The private exponent d is determined as the modular multiplicative inverse of e modulo φ(n), making d ≡ e⁻¹ (mod φ(n)). This setup is crucial as it ensures that messages encrypted with the public key (e, n) can only be decrypted by the private key (d, n).

The RSA algorithm requires that the message size be less than the modulus n. If a message is larger, it cannot be directly encrypted, and attempting to do so results in an error stating that the message is too large for the given key size. To handle messages exceeding n, the message can be split into smaller segments, each encryptable under n, or a larger key size (hence a larger n) can be used, ensuring the message falls within the acceptable range. This limitation necessitates careful key size selection during implementation to balance security and functionality .

In RSA, key size directly correlates with security and computational efficiency. Larger key sizes improve security by making it more difficult to factor the modulus n, enhancing resistance against brute-force attacks. However, larger keys also result in slower encryption and decryption processes, as exponentiation operations become more computationally intensive. The trade-off involves choosing a key size that offers sufficient security while maintaining acceptable performance. Common practice suggests using key sizes of at least 2048 bits to ensure future-proof security without severely compromising efficiency .

Choosing two distinct and large prime numbers, p and q, for RSA keys is crucial because the security of RSA is based on the difficulty of factoring the modulus n, which is the product of these primes. If the primes are not distinct, n could factor trivially, compromising security. If they are not large enough, the modulus could be factored by brute force within feasible time limits, making the encryption vulnerable to attacks. Large, distinct primes ensure that even with advanced computational resources, factoring n remains infeasible, providing secure encryption .

The security of the RSA algorithm heavily relies on the computational difficulty of factoring a large number, which is the product of two large prime numbers (p and q). The prime numbers' size is significant because the larger these primes, the more difficult it becomes to factor the modulus n back into its original prime factors, increasing the encryption strength exponentially against brute-force attacks .

The asymmetric nature of the RSA algorithm contributes to its security by using two different keys: a public key, which can be shared openly, and a private key, which is kept secret. This means that a message encrypted with the public key can only be decrypted by the corresponding private key, preventing unauthorized decryption. This one-way function ensures that even if someone intercepts the public key or the ciphertext, they cannot easily deduce the private key or original message, reinforcing security .

The mathematical consistency in the RSA algorithm between encryption and decryption is ensured through the relationship between the public and private exponents e and d, and Euler's Totient Function φ(n). For a given message m, encryption produces a ciphertext c ≡ m^e mod n and decryption then reflects back to the original message as m ≡ c^d mod n. This is guaranteed by the equation ed ≡ 1 (mod φ(n)), making (m^e)^d = m^(ed) ≡ m (mod n). This consistency is crucial because it allows messages to be securely encrypted and then accurately decrypted using the corresponding mathematical processes .

Modular arithmetic is central to RSA encryption and decryption. During encryption, a message m is raised to the power of the public exponent e and then taken modulo n to produce the ciphertext. Similarly, decryption involves raising the ciphertext to the power of the private exponent d and taking modulo n to recover the plaintext. This use of modular arithmetic enables the encryption and decryption processes to handle large numbers efficiently while maintaining the congruence relationships that ensure correctness. The security lies in the mathematical difficulty of reversing these operations without the private key, as it involves solving the integer factorization problem .

The public exponent e is commonly chosen as 65537 in RSA due to its computational efficiency and security. 65537 is a small prime number, which speeds up encryption operations (since exponentiation is faster with smaller numbers). It is also sufficiently large to safeguard against certain attacks that are feasible with smaller values, like e=3. Thus, it provides a balance between security and performance, maintaining an efficient encryption process while ensuring the public exponent is still coprime to φ(n).

You might also like