Skip to content

Commit bf16509

Browse files
Source Code
1 parent bfa8e2e commit bf16509

File tree

1 file changed

+326
-0
lines changed

1 file changed

+326
-0
lines changed

Source Code.py

Lines changed: 326 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,326 @@
1+
#Github ahmetemre3829
2+
#Ahmet Emre
3+
4+
from nacl.secret import SecretBox
5+
from nacl.utils import random
6+
import os
7+
import tkinter as tk
8+
from tkinter import filedialog
9+
import time
10+
import colorama
11+
from colorama import Fore, Style
12+
import hashlib
13+
from argon2.low_level import hash_secret_raw, Type
14+
import msvcrt
15+
16+
17+
colorama.init(autoreset=True)
18+
19+
DEFAULT_CHUNK_SIZE2 = 1 * 1024* 1024 #1MB
20+
CHUNK_SIZE2 = DEFAULT_CHUNK_SIZE2
21+
DEFAULT_CHUNK_SIZE = 2 * 1024 * 1024 # 2 MB
22+
CHUNK_SIZE = DEFAULT_CHUNK_SIZE
23+
24+
def dosya_sec():
25+
root = tk.Tk()
26+
root.withdraw()
27+
dosya_yolu = filedialog.askopenfilename(title="Şifrelemek istediğiniz dosyayı seçin")
28+
return dosya_yolu
29+
30+
31+
def calculate_hash(file_name):
32+
hash_func = hashlib.sha256()
33+
with open(file_name, 'rb') as f:
34+
total_size = os.path.getsize(file_name)
35+
hashed_size = 0
36+
start_time = time.time()
37+
while chunk:= f.read(CHUNK_SIZE2):
38+
hash_func.update(chunk)
39+
hashed_size += len(chunk)
40+
print_progress(hashed_size, total_size, start_time)
41+
return hash_func.hexdigest()
42+
43+
def calculate_hash2(file_name):
44+
hash_func = hashlib.sha256()
45+
with open(file_name, 'rb') as f:
46+
while chunk:= f.read(CHUNK_SIZE2):
47+
hash_func.update(chunk)
48+
return hash_func.hexdigest()
49+
50+
51+
def encrypt_file(file_name, key):
52+
box = SecretBox(key)
53+
54+
total_size = os.path.getsize(file_name)
55+
encrypted_size = 0
56+
57+
# Dosya adından uzantıyı ayır
58+
file_base_name, file_extension = os.path.splitext(file_name)
59+
60+
encrypted_file_path = file_name + '.enc' # Şifrelenen dosyanın yolunu oluştur
61+
dosya_adı2 = os.path.basename(encrypted_file_path)
62+
if os.path.exists(encrypted_file_path):
63+
while True:
64+
response = input(f"{Fore.YELLOW}'{dosya_adı2}' adında bir dosya zaten var. Üzerine yazmak istiyor musunuz? (e/h): ").lower()
65+
if response == 'e':
66+
break
67+
elif response == 'h':
68+
new_file_name = input("Yeni dosya adını girin: ")
69+
encrypted_file_path = os.path.join(os.path.dirname(file_name), new_file_name + file_extension + '.enc')
70+
break
71+
else:
72+
print(Fore.RED + "Geçersiz yanıt! Lütfen 'e' veya 'h' tuşlarından birini girin.")
73+
74+
start_time = time.time()
75+
try:
76+
with open(file_name, 'rb') as f, open(encrypted_file_path, 'wb') as outf:
77+
while chunk := f.read(CHUNK_SIZE):
78+
if msvcrt.kbhit() and msvcrt.getch() == b'\x1b': # ESC tuşuna basılıp basılmadığını kontrol eder
79+
print(Fore.RED + "Şifreleme işlemi iptal edildi. \n")
80+
raise KeyboardInterrupt # İşlemi durdurmak için istisna fırlatır
81+
82+
nonce = random(SecretBox.NONCE_SIZE)
83+
ciphertext = box.encrypt(chunk, nonce)
84+
outf.write(ciphertext)
85+
encrypted_size += len(chunk)
86+
print_progress(encrypted_size, total_size, start_time)
87+
88+
end_time = time.time()
89+
elapsed_time = end_time - start_time
90+
dosya_adı = os.path.basename(file_name)
91+
file_size = total_size / (1024 * 1024)
92+
encryption_speed = file_size / elapsed_time
93+
print(Fore.GREEN + f"{dosya_adı}", Fore.CYAN + f"{elapsed_time:.0f}", Fore.GREEN + "saniyede şifrelendi. Dosya Boyutu:", Fore.CYAN + f"{file_size:.1f} MB", Fore.GREEN + "Şifreleme Hızı:", Fore.CYAN + f"{encryption_speed:.0f} MB/sn")
94+
print(Fore.GREEN + "Anahtarınız:", Fore.CYAN + password,"\n")
95+
96+
except KeyboardInterrupt:
97+
# İşlem iptal edildiğinde oluşturulan dosyayı sil
98+
if os.path.exists(encrypted_file_path):
99+
os.remove(encrypted_file_path)
100+
101+
except Exception as e:
102+
print(Fore.RED + f"Hata: {e}")
103+
# Başka bir hata meydana gelirse oluşturulan dosyayı sil
104+
if os.path.exists(encrypted_file_path):
105+
os.remove(encrypted_file_path)
106+
print(Fore.RED + f"{encrypted_file_path} silindi.")
107+
108+
109+
def get_key(password):
110+
salt = b'ahmetemre' # Salt değeri sabit
111+
key_length = 32 # İstenen anahtar uzunluğu 32 byte = 256 bit
112+
113+
# Parolayı str türüne dönüştür ve ardından bayt dizisine encode et
114+
password_bytes = password.encode('utf-8')
115+
116+
# Argon2id ile hashleme yap ve belirli uzunlukta anahtar türet
117+
hashed_password = hash_secret_raw(
118+
secret=password_bytes,
119+
salt=salt,
120+
time_cost=3, # Iteration count
121+
memory_cost=65536, # Memory cost in kibibytes
122+
parallelism=2, # Parallelism factor
123+
hash_len=key_length, # Desired length of the derived key
124+
type=Type.ID # Argon2id
125+
)
126+
127+
return hashed_password
128+
129+
def generate_random_key(uzunluk):
130+
import string
131+
import random
132+
password = ''.join(random.choices(string.ascii_letters + string.digits, k=uzunluk))
133+
return password
134+
135+
def decrypt_file(file_name, key):
136+
box = SecretBox(key)
137+
total_size = os.path.getsize(file_name)
138+
decrypted_size = 0
139+
decrypted_file_path = file_name[:-4] # Çözülen dosyanın yolunu oluştur
140+
dosyam = file_name[:-4]
141+
file_base_name, file_extension = os.path.splitext(dosyam) # Dosya adından uzantıyı ayır
142+
dosya_adı3 = os.path.basename(decrypted_file_path)
143+
if os.path.exists(decrypted_file_path):
144+
overwrite_decision = input(Fore.YELLOW + f"{dosya_adı3} adında bir dosya zaten var. Üzerine yazılsın mı? (e/h): ").strip().lower()
145+
if overwrite_decision == 'h':
146+
new_file_name = input("Lütfen yeni dosya adını girin: ")
147+
decrypted_file_path = os.path.join(os.path.dirname(file_name), new_file_name + file_extension)
148+
successful = False
149+
start_time = time.time()
150+
try:
151+
with open(file_name, 'rb') as f, open(decrypted_file_path, 'wb') as outf:
152+
while chunk := f.read(CHUNK_SIZE + SecretBox.NONCE_SIZE + SecretBox.MACBYTES):
153+
if msvcrt.kbhit() and msvcrt.getch() == b'\x1b': # ESC tuşuna basılıp basılmadığını kontrol eder
154+
print(Fore.RED + "Şifre çözme işlemi iptal edildi. \n")
155+
raise KeyboardInterrupt # İşlemi durdurmak için istisna fırlatır
156+
try:
157+
decrypted_data = box.decrypt(chunk)
158+
outf.write(decrypted_data)
159+
decrypted_size += len(decrypted_data)
160+
print_progress(decrypted_size, total_size, start_time)
161+
except Exception as e:
162+
print(Fore.RED + f"Hata: {e}")
163+
print(Fore.RED + "Şifreleme anahtarınızın doğru olduğundan emin olun!\n")
164+
raise e # Hata meydana geldiğinde dıştaki try bloğuna geçer
165+
successful = True # Dosya başarıyla çözüldüğünde
166+
except KeyboardInterrupt:
167+
# İşlem iptal edildiğinde oluşturulan dosyayı sil
168+
if os.path.exists(decrypted_file_path):
169+
os.remove(decrypted_file_path)
170+
except Exception:
171+
# Eğer bir hata meydana gelirse, dosyanın silinmesini sağla
172+
if os.path.exists(decrypted_file_path):
173+
try:
174+
os.remove(decrypted_file_path)
175+
except Exception as remove_error:
176+
print(Fore.RED + f"Dosya silme hatası: {remove_error}")
177+
178+
if successful:
179+
end_time = time.time()
180+
elapsed_time = end_time - start_time
181+
dosya_adı = os.path.basename(file_name)
182+
file_size = total_size / (1024 * 1024)
183+
decryption_speed = file_size / elapsed_time
184+
print(Fore.GREEN + f"{dosya_adı}", Fore.CYAN + f"{elapsed_time:.0f}", Fore.GREEN + "saniyede şifresi çözüldü.", Fore.GREEN + "Şifre Çözme Hızı:", Fore.CYAN + f"{decryption_speed:.0f} MB/sn\n")
185+
186+
187+
188+
def print_progress(current, total, start_time):
189+
if total == 0:
190+
print(Fore.RED + "Toplam değer sıfır olamaz.", end='\r')
191+
return
192+
progress = (current / total) * 100
193+
elapsed_time = time.time() - start_time
194+
if elapsed_time == 0:
195+
speed = float('inf') # Sonsuz
196+
else:
197+
speed = (current / (1024 * 1024)) / elapsed_time
198+
if speed == 0:
199+
remaining_time = float('0')
200+
else:
201+
remaining_time = (total - current) / (1024 * 1024) / speed
202+
print(Fore.YELLOW + f"İlerleme: {progress:.0f}% - Hız: {speed:.0f} MB/sn - Kalan Süre: {remaining_time:.0f} saniye", end='\r')
203+
204+
205+
CYAN = "\033[36m"
206+
207+
banner = f"""{CYAN}
208+
┌─┐┬┌─┐┬─┐┌─┐┬ ┌─┐┌┬┐┌─┐ ┌─┐┬─┐┌─┐┌─┐┬─┐┌─┐┌┬┐┬
209+
└─┐│├┤ ├┬┘├┤ │ ├┤ │││├┤ ├─┘├┬┘│ ││ ┬├┬┘├─┤││││
210+
└─┘┴└ ┴└─└─┘┴─┘└─┘┴ ┴└─┘ ┴ ┴└─└─┘└─┘┴└─┴ ┴┴ ┴┴"""
211+
tablo = f"""
212+
╔═══════════════════╤═══════════════════╗
213+
║ 1- Şifrele │ 5- Nasıl çalışır ║
214+
╟───────────────────┼───────────────────╢
215+
║ 2- Şifre Çöz │ 6- Yapımcı ║
216+
╟───────────────────┼───────────────────╢
217+
║ 3- Chunk boyutu │ 7- Çıkış ║
218+
║ ayarla │ ║
219+
╟───────────────────╔═══════════════════╝
220+
║ 4- Dosya bütünlüğü║
221+
║ dorğula ║
222+
╚═══════════════════╝"""
223+
224+
print(banner)
225+
print(tablo)
226+
while True:
227+
try:
228+
choice = input(Fore.MAGENTA + "Seçiminiz:" + Fore.WHITE)
229+
if choice == "1":
230+
dosya = dosya_sec()
231+
dosya_adı = os.path.basename(dosya)
232+
print("Seçilen dosya:", dosya_adı)
233+
total_size = os.path.getsize(dosya)
234+
file_size = total_size / (1024 * 1024)
235+
if file_size <= 256:
236+
hash = calculate_hash2(dosya)
237+
print("Seçilen dosya hash değeri:", hash)
238+
password = input("Lütfen şifreleme anahtarı girin: ")
239+
if password.startswith('/anahtaroluştur'):
240+
uzunluk = int(password.split("/anahtaroluştur")[1]) # Girişteki sayıyı almak için bölme işlemi yapılıyor.
241+
password = generate_random_key(uzunluk)
242+
key = get_key(password)
243+
encrypt_file(dosya, key)
244+
elif choice == "2":
245+
dosya = dosya_sec()
246+
dosya_adı = os.path.basename(dosya)
247+
print("Seçilen dosya:", dosya_adı)
248+
password = input("Lütfen şifre çözme anahtarını girin: ")
249+
key = get_key(password)
250+
decrypt_file(dosya, key)
251+
elif choice == "5":
252+
print("Bu program seçilen dosyayı XChaCha20-Poly1305 şifreleme algoritmasını kullanarak şifreler. Girdiğiniz parolayı argon2 KDF algoritması kullanarak 256Bit anahtara dönüştürür.")
253+
print("Şifreleme veya çözme işlemleri sırasında işlemi iptal etmek için ESC basabilirsiniz.")
254+
print("Dosya büyüklüğüne bağlı olarak chunk boyutunu ayarlayabilirsniz. Varsayılan olarak 2 MBtır.")
255+
print("Eğer seçilen dosya 256MBtan daha küçükse hash değeri otomatik olarak yazdırılır. Bunu daha sonra şifre çözme işleminden sonra dosya bütünlüğü doğrulamak için kullanabilirsiniz.")
256+
print("Rastgele anahtar oluşturmak için anahtar sorulduğu kısımda /anahtaroluştur[x] yazmanız yeterlidir. [x] yerine karakter uzunluğu yazmalısınız.\n")
257+
elif choice == "6":
258+
print("Yapan: Ahmet Emre\nGithub: ahmetemre3829\nVersiyon: 3.4.2\n22/05/2024\n")
259+
elif choice == "3":
260+
try:
261+
chunk_input = input("İstediğiniz chunk boyutunu MB cinsinden girin: ")
262+
CHUNK_SIZE = int(chunk_input) * 1024 * 1024 if chunk_input else DEFAULT_CHUNK_SIZE
263+
print(Fore.GREEN + "Chunk boyutu",Fore.CYAN + f"{CHUNK_SIZE / (1024 * 1024):.0f}", Fore.GREEN + "MB olarak ayarlandı.\n")
264+
except ValueError:
265+
print(Fore.RED + "Hatalı giriş! Chunk boyutu 2 MB olarak ayarlandı.\n")
266+
CHUNK_SIZE = DEFAULT_CHUNK_SIZE
267+
#-----------------------------------------------------------------------------------------------------------------
268+
elif choice == "4":
269+
print("\n\n\n")
270+
print(Fore.BLUE + Style.BRIGHT + "DOSYA BÜTÜNLÜĞÜ DOĞRULAMA - SHA256")
271+
print("\n1- Hash değeri hesapla\n2- Dosya ile hash değeri karşılaştır\n3- İki hash değerini karşılaştır\n4- Chunk boyutunu ayarla\n5- Ana menüye dön\n")
272+
while True:
273+
try:
274+
inner_choice = input(Fore.MAGENTA + "Seçiminiz:" + Fore.WHITE)
275+
if inner_choice == "1":
276+
dosyas = dosya_sec()
277+
dosya_adı = os.path.basename(dosyas)
278+
print(Fore.GREEN + "Seçilen dosya:", dosya_adı)
279+
hash = calculate_hash(dosyas)
280+
print(Fore.GREEN + "SHA-256 hash değeri:",Fore.CYAN + hash, "\n")
281+
if inner_choice == "2":
282+
dosyas = dosya_sec()
283+
dosya_adı = os.path.basename(dosyas)
284+
print("Seçilen dosya:", dosya_adı)
285+
sha = input("Karşılaştırmak istediğiniz hash değerini girin: ")
286+
hash = calculate_hash(dosyas)
287+
if sha == hash:
288+
print(Fore.GREEN + "Hash değerleri eşleşiyor. Dosya doğrulandı! \n")
289+
else:
290+
print(Fore.RED + "Hash değerleri eşleşmiyor. Dosya doğrulanamadı! \n")
291+
if inner_choice == "3":
292+
hash1 = input("İlk hash değerini girin: ")
293+
hash2 = input("İkinci hash değerini girin: ")
294+
if hash1 == hash2:
295+
print(Fore.GREEN + "Hash değerleri eşleşiyor!\n")
296+
else:
297+
print(Fore.RED + "Hash değerleri eşleşmiyor!\n")
298+
if inner_choice == "4":
299+
try:
300+
chunk_input2 = input("İstediğiniz chunk boyutunu MB cinsinden girin: ")
301+
if chunk_input2.strip(): # Boş giriş kontrolü
302+
CHUNK_SIZE2 = int(chunk_input2) * 1024 * 1024 # MB cinsinden girdiyi byte'a çevirme
303+
else:
304+
CHUNK_SIZE2 = DEFAULT_CHUNK_SIZE2
305+
print(Fore.GREEN + "Chunk boyutu", Fore.CYAN + f"{CHUNK_SIZE2 / (1024 * 1024):.0f}", Fore.GREEN + "MB olarak ayarlandı.\n")
306+
except ValueError:
307+
CHUNK_SIZE2 = DEFAULT_CHUNK_SIZE2
308+
print(Fore.RED + "Hatalı giriş! Chunk boyutu 1MB olarak ayarlandı.\n")
309+
if inner_choice == "5":
310+
print("\n\n\n")
311+
print(banner)
312+
print(tablo)
313+
break
314+
except FileNotFoundError:
315+
print(Fore.RED + "Hata: Dosya bulunamadı!\n")
316+
except Exception as e:
317+
print(Fore.RED + f"Hata: {e}\n")
318+
#-----------------------------------------------------------------------------------------------------------------
319+
elif choice == "7":
320+
break
321+
else:
322+
print(Fore.RED + "Lütfen geçerli bir seçim yapın!")
323+
except FileNotFoundError:
324+
print(Fore.RED + "Hata: Dosya bulunamadı!\n")
325+
except Exception as e:
326+
print(Fore.RED + f"Hata: {e}\n")

0 commit comments

Comments
 (0)