-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathencryptor.py
More file actions
54 lines (44 loc) · 1.79 KB
/
Copy pathencryptor.py
File metadata and controls
54 lines (44 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import os
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
class Encryptor:
def __init__(self, config: dict):
self.public_key_path = os.getcwd() + '/encryption/rsa/public_key.pem'
self.private_key_path = os.getcwd() + '/encryption/rsa/private_key.pem'
self.chunk_size = 128
def encrypt(self, data):
offset = 0
encrypted = "".encode()
fp = open(self.public_key_path, 'rb')
rsa_key = RSA.importKey(fp.read().decode())
oaep_encryptor = PKCS1_OAEP.new(rsa_key)
fp.close()
print(len(data))
while offset < len(data):
chunk = data[offset:offset + self.chunk_size]
if len(chunk) % self.chunk_size != 0:
try:
chunk += " " * (self.chunk_size - len(chunk))
except TypeError:
chunk = chunk.decode()
chunk += " " * (self.chunk_size - len(chunk))
print('0enc length ' + str(len(chunk)))
try:
bin_chunk = chunk.encode()
except AttributeError:
# chunk is already here
bin_chunk = chunk
print('1enc length ' + str(len(bin_chunk)))
encrypted_chunk = oaep_encryptor.encrypt(bin_chunk)
print('11enc length ' + str(len(encrypted_chunk)))
encrypted += encrypted_chunk
offset += self.chunk_size
return encrypted
def decrypt(self, data):
print('\n ...decrypting... \n')
priv_key_file = open(self.private_key_path, 'rb')
rsa_key = RSA.importKey(priv_key_file.read().decode())
decryptor = PKCS1_OAEP.new(rsa_key)
priv_key_file.close()
decrypted = decryptor.decrypt(data).decode()
return decrypted