-->

Cara MengEnkripsi & Dekripsi File Gambar Menggunakan Python

Kriptografi adalah proses menyembunyikan informasi dengan cara mengkonversi data yang dapat dibaca, kedalam data yang tidak bisa dibaca menggunakan sejumlah kunci (key) atau algoritma enkripsi.

Apa saja yang bisa kita enkripsi? Informasi yang dapat kita enkripsi menggunakan kriptografi meliputi email, gambar, video, file dan data sensitif lainnya.

Tujuan dari kriptografi adalah untuk memastikan informasi yang terenkripsi selalu tetap rahasia, integritas, otentikasi dan asli tidak terbantahkan (non-repudiation).

Library yang digunakan cryptography

Install Library dengan cara : 

pip install cryptography

nanti outputnya di shell kalian seperti ini:

Installing collected packages: cryptography
Successfully installed cryptography-42.0.8

Generate Script : 


Script berikut untuk Mengenkripsi File Gambar Save dengan nama, Enkripsi.py :

from cryptography.fernet import Fernet

key = Fernet.generate_key()

with open('key.key', 'wb') as f:
    f.write(key)

print("Key has been generated and saved.")

# Load the key from the file
with open('key.key', 'rb') as f:
    key = f.read()

# Create a Fernet object with the key
fernet = Fernet(key)

# Read the image to be encrypted
with open('img.jpg', 'rb') as f:
    photo = f.read()

# Encrypt the image
locked_photo = fernet.encrypt(photo)

# Write the encrypted image to a new file
with open('locked_img.jpg', 'wb') as locked_photo_file:
    locked_photo_file.write(locked_photo)

print("Image has been encrypted and saved.")

Decryption Process : 

from cryptography.fernet import Fernet

# Load the key from the file
with open('key.key', 'rb') as f:
    key = f.read()

# Create a Fernet object with the key
fernet = Fernet(key)

# Read the encrypted image
with open('locked_img.jpg', 'rb') as f:
    locked_photo = f.read()

# Decrypt the image
unlocked_photo = fernet.decrypt(locked_photo)

# Write the decrypted image to a new file
with open('unlocked_img.jpg', 'wb') as unlocked_photo_file:
    unlocked_photo_file.write(unlocked_photo)

print("Image has been decrypted and saved.")



Sumber : python.plainenglish , bisa.ai
See Also :