-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathencryption.py
39 lines (32 loc) · 1.2 KB
/
encryption.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
from Crypto import Random
from Crypto.Cipher import AES
import os
class Encryptor:
def __init__(self,key):
self.key = key
def pad(self,s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)
def encrypt(self, message, key, key_size=256):
message = self.pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
def encrypt_file(self, file_name):
with open(file_name, 'rb') as fo:
plaintext = fo.read()
enc = self.encrypt(plaintext, self.key)
with open(file_name + ".enc", 'wb') as fo:
fo.write(enc)
os.remove(file_name)
def decrypt(self, ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return plaintext.rstrip(b"\0")
def decrypt_file(self, file_name):
with open(file_name, 'rb') as fo:
ciphertext = fo.read()
dec = self.decrypt(ciphertext, self.key)
with open(file_name[:-4], 'wb') as fo:
fo.write(dec)
os.remove(file_name)