-
Notifications
You must be signed in to change notification settings - Fork 5
/
Encryptor.py
95 lines (81 loc) · 2.85 KB
/
Encryptor.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 14:35:29 2019
@author: Adamlkl
"""
'''
https://docs.python-guide.org/scenarios/crypto/
'''
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
# generate normal key
def generate_key():
key = Fernet.generate_key()
return key
# generates a new RSA private key using the provided backend with 2048 bits
def generate_private_key():
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend())
return private_key
# encrypt symmetric key using public key passed
def encrypt_symmetric_key(public_key, sym_key):
encrypted_key = public_key.encrypt(
sym_key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return encrypted_key
# encrypt plain text using key passed
def encrypt(plain_text, key):
cipher_suite = Fernet(key)
return cipher_suite.encrypt(plain_text)
# decrypt encrypted text using key passed
def decrypt(encrypted_text, key):
cipher_suite = Fernet(key)
return cipher_suite.decrypt(encrypted_text)
# -----------------testing functions--------------------------------------
def encryptt(filename, key):
cipher_suite = Fernet(key)
plain_file = open(filename, "rb")
plain_text = plain_file.read()
plain_file.close()
encrypted_text = cipher_suite.encrypt(plain_text)
encrypted_file = open(filename+".aes", "wb+")
encrypted_file.write(encrypted_text)
encrypted_file.close()
def decryptt(filename, key):
cipher_suite = Fernet(key)
'''
with open(os.path.join("EncryptedFiles",filename), 'rb') as encrypted_file:
encrypted_text = encrypted_file.read()
encrypted_file.close()
'''
encrypted_file = open(filename+".aes", "rb")
encrypted_text = encrypted_file.read()
encrypted_file.close()
decrypted_text = cipher_suite.decrypt(encrypted_text)
if '/' in filename:
index = filename.rfind('/')
format_name = filename[0:index]
format_name = format_name + "/decrypted_"
format_name = format_name + filename[index+1:]
decrypted_file = open(format_name, "wb+")
else:
decrypted_file = open("decrypted_"+filename, "wb+")
decrypted_file.write(decrypted_text)
decrypted_file.close()
def main():
key = generate_key()
encrypt("testfiles/COPYLIST.txt",key)
decrypt("testfiles/COPYLIST.txt",key)
if __name__ == '__main__':
main()