0% found this document useful (0 votes)
15 views

Rsa Algorithm

The document discusses the RSA algorithm for public-key cryptography. It describes how RSA uses a public and private key pair to encrypt and decrypt messages. The keys are derived from two large prime numbers. Several functions are provided to generate the keys, encrypt and decrypt messages, and an example is shown of encrypting a message with the public key and decrypting it with the private key.

Uploaded by

Khalida
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Rsa Algorithm

The document discusses the RSA algorithm for public-key cryptography. It describes how RSA uses a public and private key pair to encrypt and decrypt messages. The keys are derived from two large prime numbers. Several functions are provided to generate the keys, encrypt and decrypt messages, and an example is shown of encrypting a message with the public key and decrypting it with the private key.

Uploaded by

Khalida
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

rsa-algorithm

May 16, 2024

1 Asymmetric Cryptography
Public-key cryptography, or asymmetric cryptography, is a cryptographic system that uses pairs of
keys: public keys, which may be disseminated widely, and private keys,which are known only to the
owner. The generation of such keys depends on cryptographic algorithms based on mathematical
problems to produce one-way functions. Effective security only requires keeping the private key
private; the public key can be openly distributed without compromising security.
In such a system, any person can encrypt a message using the receiver’s public key, but that
encrypted message can only be decrypted with the receiver’s private key.
Robust authentication is also possible. A sender can combine a message with a private key to create
a short digital signature on the message. Anyone with the sender’s corresponding public key can
combine the same message and the supposed digital signature associated with it to verify whether
the signature was valid, i.e. made by the owner of the corresponding private key.
Public key algorithms are fundamental security ingredients in modern cryptosystems, applications
and protocols assuring the confidentiality, authenticity and non-repudiability of electronic commu-
nications and data storage. They underpin various Internet standards, such as Transport Layer
Security (TLS), S/MIME, PGP, and GPG. Some public key algorithms provide key distribution and
secrecy (e.g., Diffie–Hellman key exchange), some provide digital signatures (e.g., Digital Signature
Algorithm), and some provide both (e.g., RSA).

2 RSA Algorithm
RSA (Rivest–Shamir–Adleman) is one of the first public-key cryptosystems and is widely used
for secure data transmission. In such a cryptosystem, the encryption key is public and distinct
from the decryption key which is kept secret (private). In RSA, this asymmetry is based on the
practical difficulty of factoring the product of two large prime numbers, the “factoring problem”.
The acronym RSA is the initial letters of the surnames of Ron Rivest, Adi Shamir, and Leonard
Adleman, who publicly described the algorithm in 1977. Clifford Cocks, an English mathematician
working for the British intelligence agency Government Communications Headquarters (GCHQ),
had developed an equivalent system in 1973, which was not declassified until 1997.
A user of RSA creates and then publishes a public key based on two large prime numbers, along
with an auxiliary value. The prime numbers must be kept secret. Anyone can use the public key
to encrypt a message, but only someone with knowledge of the prime numbers can decode the
message. Breaking RSA encryption is known as the RSA problem. Whether it is as difficult as the
factoring problem is an open question. There are no published methods to defeat the system if a
large enough key is used.

1
RSA is a relatively slow algorithm, and because of this, it is less commonly used to directly encrypt
user data. More often, RSA passes encrypted shared keys for symmetric key cryptography which
in turn can perform bulk encryption-decryption operations at much higher speed.

2.1 Helper functions to convert from string to decimal values and from decimal
values to string
[1]: # Converts a string to a list of decimal numbers
def str2dec(st):
dec_list = []
for i in st:
dec_list.append(ord(i))
return dec_list

# Converts a list of decimal numbers to string


def dec2str(dec):
str_list = []
for i in dec:
str_list.append(chr(i))
return ''.join(str_list)

message = 'Test'
print('Original String: \t', message)

dec = str2dec(message)
print('String into Decimal: \t', dec)

txt = dec2str(dec)
print('Decimal into String: \t', txt)

Original String: Test


String into Decimal: [84, 101, 115, 116]
Decimal into String: Test

2.2 Prime number generator


Generates random prime number given a value range.
[2]: import random
import math

def generate_prime(beg=1000, end=10000):


beg_rand = random.randint(beg, end);
if beg_rand % 2 == 0:
beg_rand += 1

for possiblePrime in range(beg_rand, end, 2):

2
# Assume number is prime until shown it is not.
isPrime = True
for num in range(3, math.floor(possiblePrime/2), 2):
if possiblePrime % num == 0:
isPrime = False

if isPrime:
return possiblePrime

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 multiplication of two large prime numbers. And
private key is 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.

2.3 Public and Private key generation


The public key corresponds to the pair {e, n} 𝑒 needs to be: * 1 < 𝑒 < 𝜙(𝑛) * coprime
with 𝑛 and 𝜙(𝑛)
𝜙(𝑛) = (𝑝 − 1) ∗ (𝑞 − 1) = the total number of coprimes with n

[3]: # This value is the multiplication of the two prime numbers,


# because the prime numbers are large this value is difficult to factorize
def generate_nkey(p, q):
return p * q

# This 'e' key with 'n' is considered the public key


def generate_ekey(p, q):
phi = (p-1) * (q-1)

for e in range(random.randrange(3, phi-1, 2), phi-1):


if math.gcd(e, phi) == 1:
return e

The private key corresponds to the pair {d, n} 𝑑 needs to be: * 𝑑𝑒(𝑚𝑜𝑑𝜙(𝑛)) = 1

[4]: # This 'd' key with 'n' is considered the private key
def generate_dkey(e):
phi = (p-1) * (q-1)

d = int(phi / e)
while (True):
if (d * e) % phi == 1:
return d
d += 1

3
2.4 Encryption and Decryption algorithm
The formula used to both encrypt and decrypt the messages is the same. All messages that are
encrypted with the public key can only be decrypted with the private key, and messages encrypted
with the private key can only be decrypted with the public key.
[5]: def endecrypt_message(m, key, n):

res = 1 # Initialize result

# Update message if it is more than or equal to p


m = m % n

if (m == 0) :
return 0

while (key > 0) :

# If key is odd, multiply key with result


if ((key & 1) == 1) :
res = (res * m) % n

# key must be even now


key = key >> 1 # key = key/2
m = (m * m) % n

return res

3 Example
[6]: p = generate_prime()
q = generate_prime()

while (p == q):
q = generate_prime()

print('Two random prime numbers')


print('\tPrime 1: ', p)
print('\tPrime 2: ', q)

n = generate_nkey(p, q)
e = generate_ekey(p, q)
d = generate_dkey(e)

print('\nn key: ', n)


print('e key: ', e)
print('d key: ', d)

4
print('\nPublic key {e, n}: {%d, %d}' %(e, n))
print('Private key {d, n}: {%d, %d}' %(d, n))

Two random prime numbers


Prime 1: 7393
Prime 2: 8069

n key: 59654117
e key: 23376623
d key: 41952143

Public key {e, n}: {23376623, 59654117}


Private key {d, n}: {41952143, 59654117}

3.1 Encrypting with the public key and decrypting with the private key
Once the massage in encrypted using the public key, it can only be decrypted by owner of the
private key, this way, the message cannot be modified during the transmition.
[7]: message = 'Ibis Prevedello'
message_dec = str2dec(message)

# Encrypt message using the public key


encrypted = [endecrypt_message(i, e, n) for i in message_dec]

# Decrypt message using the private key


decrypted = [endecrypt_message(i, d, n) for i in encrypted]

print('\nMESSAGE\n\t', message, '\n\t', message_dec)


print('\n\nENCRYPTED\n\t', encrypted)
print('\n\nDECRYPTED\n\t', dec2str(decrypted), '\n\t', decrypted)

MESSAGE
Ibis Prevedello
[73, 98, 105, 115, 32, 80, 114, 101, 118, 101, 100, 101, 108, 108, 111]

ENCRYPTED
[2299003, 19829760, 30340827, 16915268, 22806790, 31328377, 52034573,
15679620, 55233940, 15679620, 46972104, 15679620, 40264816, 40264816, 10178222]

DECRYPTED
Ibis Prevedello
[73, 98, 105, 115, 32, 80, 114, 101, 118, 101, 100, 101, 108, 108, 111]

5
3.2 Encrypting with the private key and decrypting with the public key
The idea here is to show that the opposit is also valid, it does not really make sense to encrypt
messages using the private key, because the public key is known to everyone, this way anyone could
decrypt it. But the encryption with the public key is used to prove that the message really came
from the owner of the private key.
[8]: message = 'Ibis Prevedello'
message_dec = str2dec(message)

# Encrypt message using the private key


encrypted = [endecrypt_message(i, d, n) for i in message_dec]

# Decrypt message using the public key


decrypted = [endecrypt_message(i, e, n) for i in encrypted]

print('\nMESSAGE\n\t', message, '\n\t', message_dec)


print('\n\nENCRYPTED\n\t', encrypted)
print('\n\nDECRYPTED\n\t', dec2str(decrypted), '\n\t', decrypted)

MESSAGE
Ibis Prevedello
[73, 98, 105, 115, 32, 80, 114, 101, 118, 101, 100, 101, 108, 108, 111]

ENCRYPTED
[2573418, 41200476, 26690502, 49479559, 56054585, 46859964, 50266683,
29662549, 49748881, 29662549, 18778234, 29662549, 29596224, 29596224, 47908214]

DECRYPTED
Ibis Prevedello
[73, 98, 105, 115, 32, 80, 114, 101, 118, 101, 100, 101, 108, 108, 111]

You might also like