-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAES_simpleClass.py
More file actions
66 lines (52 loc) · 2.13 KB
/
AES_simpleClass.py
File metadata and controls
66 lines (52 loc) · 2.13 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
55
56
57
58
59
60
61
62
63
64
65
66
import hashlib
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
class AESCipher:
def __init__(self, file_name, key):
self.file_name = file_name
self.key = self._hash_key(key)
def _hash_key(self, key):
# Hash the key using SHA-256 to generate a 32-byte key
hashed_key = hashlib.sha256(key.encode()).digest()
return hashed_key
def encrypt(self):
# Read the plaintext from the file
with open(self.file_name, 'rb') as f:
plaintext = f.read()
# Create AES cipher object with the hashed key
cipher = AES.new(self.key, AES.MODE_CBC)
# Pad the plaintext to be a multiple of 16 bytes
padded_plaintext = pad(plaintext, AES.block_size)
# Encrypt the plaintext
ciphertext = cipher.encrypt(padded_plaintext)
# Write the ciphertext to a new file
with open(self.file_name + '.enc', 'wb') as f:
f.write(cipher.iv)
f.write(ciphertext)
def decrypt(self):
# Read the initialization vector and ciphertext from the file
with open(self.file_name, 'rb') as f:
iv = f.read(16)
ciphertext = f.read()
# Create AES cipher object with the hashed key and the initialization vector
cipher = AES.new(self.key, AES.MODE_CBC, iv)
# Decrypt the ciphertext
decrypted_data = cipher.decrypt(ciphertext)
# Unpad the decrypted data
unpadded_data = unpad(decrypted_data, AES.block_size)
# Write the decrypted plaintext to a new file
with open(os.path.splitext(self.file_name)[0] + '_decrypted.txt', 'wb') as f:
f.write(unpadded_data)
# Example usage:
file_name = input("Enter the name of the file to encrypt: ")
key = input("Enter the encryption key: ")
cipher = AESCipher(file_name, key)
cipher.encrypt()
print("File encrypted successfully.")
# To decrypt:
# decrypted_file_name = input("Enter the name of the file to decrypt: ")
# key = input("Enter the encryption key: ")
# cipher = AESCipher(decrypted_file_name, key)
# cipher.decrypt()
# print("File decrypted successfully.")