| from base64 import b64encode, b64decode |
| import hashlib |
| from Crypto.Cipher import AES |
| from Crypto.Random import get_random_bytes |
| from Crypto.Util.Padding import pad, unpad |
|
|
|
|
| def encrypt(image_path, key): |
| |
| with open(image_path, 'rb') as f: |
| image_data = f.read() |
|
|
| |
| image_data = b64encode(image_data) |
|
|
| |
| key = hashlib.sha256(key.encode()).digest() |
|
|
| |
| iv = get_random_bytes(AES.block_size) |
|
|
| |
| cipher = AES.new(key, AES.MODE_CBC, iv) |
|
|
| |
| encrypted_image_data = cipher.encrypt(pad(image_data, AES.block_size)) |
|
|
| |
| with open(image_path + '.enc', 'wb') as f: |
| f.write(iv + encrypted_image_data) |
|
|
|
|
| def decrypt(encrypted_image_path, key): |
| |
| with open(encrypted_image_path, 'rb') as f: |
| encrypted_image_data = f.read() |
|
|
| |
| key = hashlib.sha256(key.encode()).digest() |
|
|
| |
| iv = encrypted_image_data[:AES.block_size] |
| encrypted_image_data = encrypted_image_data[AES.block_size:] |
|
|
| |
| cipher = AES.new(key, AES.MODE_CBC, iv) |
|
|
| try: |
| |
| decrypted_image_data = unpad(cipher.decrypt(encrypted_image_data), AES.block_size) |
|
|
| |
| decrypted_image_data = b64decode(decrypted_image_data) |
|
|
| |
| filename = encrypted_image_path.replace('.enc', '').replace('.png', '').replace('.jpg', '') + '.dec' + '.png' |
| with open(filename, 'wb') as f: |
| f.write(decrypted_image_data) |
|
|
| except ValueError: |
| print("Wrong Key ):") |
| return -1, None |
| return 0, filename |
|
|
|
|