Skip to content

Commit 8071cad

Browse files
RSA script added with README (HarshCasper#855)
* RSA script added * Readme ammended * Readme ammended * Readme ammended * Readme ammended * Readme ammended * RSA Error resolved * Converted Tab Indentatio to Spaces * Added EOF Line * Added EOF Line * Delete RSA_algorithm.txt * Added EOF Line Co-authored-by: Harsh Mishra <[email protected]>
1 parent 529b2c3 commit 8071cad

File tree

6 files changed

+199
-12
lines changed

6 files changed

+199
-12
lines changed

Python/RSA_Key_Generation/README.md

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,33 @@
22
## This script is used to create a private/public keypair for SSH-authentication for password-less connecting to a remote server.
33

44
+ On running this script, will create two files with (.pem) format which contains public and private key.
5-
+ Defined length of keys are 2048 bits *(recommended size)* which determines the strength of keys.
5+
+ Defined length of keys are 4096 bits *(recommended size)* which determines the strength of keys.
66

77
## To run the script:
88
1. Install the dependencies by running following command in terminal.
99

1010
`pip install pycryptodome`
11+
1112
2. Run the script.
1213

13-
`python rsa_key_generation.py`
14+
`python RSA.py`
15+
16+
The script runs until you enter valid commands-
17+
1) generate_keys \<folder path to store keys\>
18+
19+
\(eg - `generate_keys ./keys`\)
20+
21+
2) encrypt \<path to public key file\> \<file to encrypt\> \<encrypted file name\>
22+
23+
\(eg - `encrypt ./keys/public_key.pem nature.jpeg enc_script`\)
24+
25+
3) decrypt \<path to private key file\> \<file to decrypt\> \<decrypted file name\>
26+
27+
\(eg - `decrypt ./keys/private_key.pem enc_script NATURE.jpeg` \)
28+
29+
4) exit- to exit from the program
30+
31+
\(eg - `exit`\)
1432

1533
In case, if you want to know more, Read complete documentation [here](https://pycryptodome.readthedocs.io/en/latest/src/public_key/rsa.html)
1634

Python/RSA_Key_Generation/RSA.py

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
import sys
2+
from Crypto.PublicKey import RSA
3+
from Crypto.Cipher import PKCS1_OAEP
4+
import zlib
5+
import base64
6+
from keyPair_generation import keyPairGeneration
7+
from utilities import Utilities
8+
9+
10+
class RSA_algorithm:
11+
def encrypt(self, public_key, blob):
12+
#Import the Public Key and use for encryption using PKCS1_OAEP
13+
rsa_key = RSA.importKey(public_key)
14+
rsa_key = PKCS1_OAEP.new(rsa_key)
15+
16+
#compress the data first
17+
blob = zlib.compress(blob)
18+
19+
'''In determining the chunk size, determine the private key length used in bytes and subtract 42 bytes
20+
(when using PKCS1_OAEP). The data will be in encrypted in chunks'''
21+
chunk_size = 470
22+
offset = 0
23+
end_loop = False
24+
encrypted = b''
25+
26+
while not end_loop:
27+
#The chunk
28+
chunk = blob[offset:offset + chunk_size]
29+
30+
#If the data chunk is less then the chunk size, then we need to add
31+
#padding with " ". This indicates the we reached the end of the file
32+
#so we end loop here
33+
if len(chunk) % chunk_size != 0:
34+
end_loop = True
35+
chunk += b'' * (chunk_size - len(chunk))
36+
37+
#Append the encrypted chunk to the overall encrypted file
38+
encrypted += rsa_key.encrypt(chunk)
39+
40+
#Increase the offset by chunk size
41+
offset += chunk_size
42+
43+
#Base 64 encode the encrypted file
44+
return base64.b64encode(encrypted)
45+
46+
def decrypt(self, private_key, encrypted_blob):
47+
#Import the Private Key and use for decryption using PKCS1_OAEP
48+
rsakey = RSA.importKey(private_key)
49+
rsakey = PKCS1_OAEP.new(rsakey)
50+
51+
#Base 64 decode the data
52+
encrypted_blob = base64.b64decode(encrypted_blob)
53+
54+
#In determining the chunk size, determine the private key length used in bytes.
55+
#The data will be in decrypted in chunks
56+
chunk_size = 512
57+
offset = 0
58+
decrypted = b''
59+
60+
#keep loop going as long as we have chunks to decrypt
61+
while offset < len(encrypted_blob):
62+
#The chunk
63+
chunk = encrypted_blob[offset: offset + chunk_size]
64+
65+
#Append the decrypted chunk to the overall decrypted file
66+
decrypted += rsakey.decrypt(chunk)
67+
68+
#Increase the offset by chunk size
69+
offset += chunk_size
70+
71+
#return the decompressed decrypted data
72+
return zlib.decompress(decrypted)
73+
74+
75+
76+
if __name__ == '__main__':
77+
while True:
78+
command= input().strip().split(' ')
79+
80+
# if the user demands to generate the key pair
81+
if command[0] == 'generate_keys':
82+
try:
83+
filePath_for_Keys= command[1]
84+
kpg= keyPairGeneration(filePath_for_Keys)
85+
except:
86+
print ("Please verify the file path(s) given.")
87+
88+
# if the user demands to encrypt some confidential file
89+
elif command[0] == 'encrypt':
90+
try:
91+
# extract the path of the public key file
92+
filePath_of_PublicKey= command[1]
93+
# extract the path of the file to be encrypted
94+
file_to_encrypt= command[2]
95+
# extract the filename user demands to give to will be formed encrypted file
96+
encrypted_filename= command[3]
97+
98+
# creating object of utilities to access
99+
util= Utilities()
100+
101+
# read the public key
102+
publicKey= util.readFile(filePath_of_PublicKey)
103+
# read the to be encrypted content
104+
unencrypted_blob= util.readFile(file_to_encrypt)
105+
106+
rsa= RSA_algorithm()
107+
# encrypt the content
108+
encrypted_blob= rsa.encrypt(publicKey, unencrypted_blob)
109+
# write the encrypted blob to get the encrypted contents of the file
110+
util.writeFile(encrypted_filename, encrypted_blob)
111+
112+
except:
113+
print ("Please verify the file path(s) given.")
114+
115+
# if the user demands to decrypt some encrypted file
116+
elif command[0] == 'decrypt':
117+
try:
118+
# extract the path of the private key file
119+
filePath_of_PrivateKey= command[1]
120+
# extract the path of the file to be decrypted
121+
file_to_decrypt= command[2]
122+
# extract the filename user demands to give to will be formed decrypted file
123+
decrypted_filename= command[3]
124+
125+
# creating object of utilities to access
126+
util= Utilities()
127+
128+
# read the private key
129+
privateKey= util.readFile(filePath_of_PrivateKey)
130+
# read the to be decrypted content
131+
encrypted_blob= util.readFile(file_to_decrypt)
132+
133+
rsa= RSA_algorithm()
134+
# decrypt the content
135+
decrypted_blob= rsa.decrypt(privateKey, encrypted_blob)
136+
# write the decrypted blob to get the original contents of file
137+
util.writeFile(decrypted_filename, decrypted_blob)
138+
139+
except:
140+
print ("Please verify the file path(s) given.")
141+
142+
# user demads to exit from the program
143+
elif command[0] == 'exit':
144+
break
145+
146+
else:
147+
print ("Invalid Command, please verify from the manual.")
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#ch9_generate_keys.py
2+
from Crypto.PublicKey import RSA
3+
from utilities import Utilities
4+
5+
class keyPairGeneration:
6+
def __init__(self, filePath):
7+
#Generate a public/ private key pair using 4096 bits key length (512 bytes)
8+
new_key = RSA.generate(4096, e=65537)
9+
10+
# creating object of utilities to access
11+
util= Utilities()
12+
13+
#The private key in PEM format
14+
private_key = new_key.exportKey("PEM")
15+
# write the private key
16+
util.writeFile(filePath+"/private_key.pem", private_key)
17+
18+
#The public key in PEM Format
19+
public_key = new_key.publickey().exportKey("PEM")
20+
#write the public key
21+
util.writeFile(filePath+"/public_key.pem", public_key)

Python/RSA_Key_Generation/key_pair_generation.py

Lines changed: 0 additions & 10 deletions
This file was deleted.

Python/RSA_Key_Generation/nature.jpeg

11.3 KB
Loading
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Utilities:
2+
def writeFile(self, filename, content):
3+
file_ptr = open(filename, "wb")
4+
file_ptr.write(content)
5+
file_ptr.close()
6+
7+
def readFile(self, filename):
8+
file_ptr = open(filename, "rb")
9+
content = file_ptr.read()
10+
file_ptr.close()
11+
return content

0 commit comments

Comments
 (0)