Css Exp 3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Vidya Vikas Education Trust’s

Universal College of Engineering, Kaman Road, Vasai-401208


Accredited by B+ Grade by NAAC

Experiment No 3

Aim: To implement the RSA algorithm.

Theory:

Introduction

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, the Public
Key is given to everyone and the Private key is kept private.
An example of asymmetric cryptography:
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.
3. The client receives this data and decrypts it.

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.
The idea! The idea of RSA is based on the fact that it is difficult to factorize a large integer. The
public key consists of two numbers where one number is a multiplication of two large prime
numbers. And private keys are also derived from the same two prime numbers. So if somebody
can factorize the large number, the private key is compromised. Therefore encryption strength
totally lies on the key size and if we double or triple the key size, the strength of encryption
increases exponentially. RSA keys can be typically 1024 or 2048 bits long, but experts believe
that 1024-bit keys could be broken in the near future. But till now it seems to be an infeasible
task.
Algorithm

RSA encryption algorithm is a type of public-key encryption algorithm. To better understand


RSA, let's first understand what a public-key encryption algorithm is.

Public key encryption algorithm:


Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

The Public Key encryption algorithm is also called the Asymmetric algorithm. Asymmetric
algorithms are those algorithms in which sender and receiver use different keys for encryption
and decryption. Each sender is assigned a pair of keys:

● Public key

● Private key

The Public key is used for encryption, and the Private Key is used for decryption. Decryption
cannot be done using a public key. The two keys are linked, but the private key cannot be derived
from the public key. The public key is well known, but the private key is secret and it is known
only to the user who owns the key. It means that everybody can send a message to the user using
the user's public key. But only the user can decrypt the message using his private key.

The Public key algorithm operates in the following manner:

● The data to be sent is encrypted by sender A using the public key of the intended receiver
Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

● B decrypts the received ciphertext using its private key, which is known only to B. B
replies to A encrypting its message using A's public key.

● A decrypts the received ciphertext using its private key, which is known only to him.

RSA encryption algorithm:

RSA is the most common public-key algorithm, named after its inventors Rivest, Shamir, and
Adelman (RSA).

RSA algorithm uses the following procedure to generate public and private keys:

● Select two large prime numbers, p and q.

● 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
Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

● 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

Program

from math import sqrt

#required for the sqrt() function, if you want to avoid doing **0.5

import random

#required for randrange

from random import randint as rand

#just to use the well known keyword rand() from C++


Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

def gcd(a, b):

if b == 0:

return a

else:

return gcd(b, a % b)

def mod_inverse(a, m):

for x in range(1, m):

if (a * x) % m == 1:

return x

return -1

def isprime(n):

if n < 2:

return False

elif n == 2:

return True
Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

else:

for i in range(2, int(sqrt(n)) + 1, 2):

if n % i == 0:

return False

return True

#initial two random numbers p,q

p = rand(1, 1000)

q = rand(1, 1000)

def generate_keypair(p, q, keysize):

# keysize is the bit length of n so it must be in range(nMin,nMax+1).

# << is bitwise operator

# x << y is same as multiplying x by 2**y

# i am doing this so that p and q values have similar bit-length.

# this will generate an n value that's hard to factorize into p and q.

nMin = 1 << (keysize - 1)


Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

nMax = (1 << keysize) - 1

primes = [2]

# we choose two prime numbers in range(start, stop) so that the difference of bit lengths is at
most 2.

start = 1 << (keysize // 2 - 1)

stop = 1 << (keysize // 2 + 1)

if start >= stop:

return []

for i in range(3, stop + 1, 2):

for p in primes:

if i % p == 0:

break

else:

primes.append(i)

while (primes and primes[0] < start):


Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

del primes[0]

#choosing p and q from the generated prime numbers.

while primes:

p = random.choice(primes)

primes.remove(p)

q_values = [q for q in primes if nMin <= p * q <= nMax]

if q_values:

q = random.choice(q_values)

break

print(p, q)

n=p*q

phi = (p - 1) * (q - 1)

#generate public key 1<e<phi(n)

e = random.randrange(1, phi)

g = gcd(e, phi)
Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

while True:

#as long as gcd(1,phi(n)) is not 1, keep generating e

e = random.randrange(1, phi)

g = gcd(e, phi)

#generate private key

d = mod_inverse(e, phi)

if g == 1 and e != d:

break

#public key (e,n)

#private key (d,n)

return ((e, n), (d, n))

def encrypt(msg_plaintext, package):

#unpack key value pair

e, n = package

msg_ciphertext = [pow(ord(c), e, n) for c in msg_plaintext]


Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

return msg_ciphertext

def decrypt(msg_ciphertext, package):

d, n = package

msg_plaintext = [chr(pow(c, d, n)) for c in msg_ciphertext]

# No need to use ord() since c is now a number

# After decryption, we cast it back to character

# to be joined in a string for the final result

return (''.join(msg_plaintext))

#-------------------------------------------------------------

#driver program

if __name__ == "__main__":

bit_length = int(input("Enter bit_length: "))

print("Running RSA...")

print("Generating public/private keypair...")

public, private = generate_keypair(


Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

p, q, 2**bit_length) # 8 is the keysize (bit-length) value.

print("Public Key: ", public)

print("Private Key: ", private)

msg = input("Write msg: ")

print([ord(c) for c in msg])

encrypted_msg = encrypt(msg, public)

print("Encrypted msg: ")

print(''.join(map(lambda x: str(x), encrypted_msg)))

print("Decrypted msg: ")

print(decrypt(encrypted_msg, private))
Vidya Vikas Education Trust’s
Universal College of Engineering, Kaman Road, Vasai-401208
Accredited by B+ Grade by NAAC

Output

Conclusion:
It is concluded that, while establishing RSA key pairs, usage keys and general-purpose keys are
integrated. In RSA keys, two key pairs are used for encryption and signatures. In the
General-purpose key, one single pair is used for both encryption and signature.

You might also like