Caesar Shifri
Klassik
Oson
Caesar shifri tarixi
Rim imperatori Yuliy Sezar harbiy xabarlarini himoya qilish uchun bu usulni ishlatgan. Har harfni alfavitda ma'lum son (odatda 3) ga surgan.
"Agar Sezar harbiy sirlarini yozishga ehtiyoj sezsa, u harflarni almashtirardi: A ni D bilan, B ni E bilan..." — Suetonius
Qanday ishlaydi?
Har bir harfni alfavitda K ta o'ringa suring (K = kalit):
Asl: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
K=3: D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
Python bilan shifrlash
def caesar_encrypt(text: str, shift: int) -> str:
result = []
for char in text.upper():
if char.isalpha():
# Harfni raqamga o'tkazish (A=0, B=1, ...)
num = ord(char) - ord('A')
# Siljitish va modulo 26 (alfavit chegarasi)
shifted = (num + shift) % 26
result.append(chr(shifted + ord('A')))
else:
result.append(char) # Harf bo'lmasa o'zgarmasdan
return ''.join(result)
def caesar_decrypt(text: str, shift: int) -> str:
return caesar_encrypt(text, -shift) # Teskarisi
# Misol
matn = "SALOM DUNYO"
encrypted = caesar_encrypt(matn, 3)
print("Shifrlangan:", encrypted) # VDORP GXQBR
decrypted = caesar_decrypt(encrypted, 3)
print("Deshifrlangan:", decrypted) # SALOM DUNYO
Brute Force (barcha variantlarni sinash)
def brute_force_caesar(ciphertext: str):
print("Barcha 26 ta variant:")
for shift in range(26):
decrypted = caesar_decrypt(ciphertext, shift)
print(f" Siljish {shift:2d}: {decrypted}")
brute_force_caesar("AHYY{oehgr_sbepvat_pnrfne}")
# Siljish 13: NULL{brute_forcing_caesar} ← To'g'ri javob!
ROT13 — maxsus holat
import codecs
# ROT13 = siljish 13 (o'zi o'zining teskarisi!)
text = "Salom"
rot13 = codecs.encode(text, 'rot_13')
print(rot13) # Fnyby
print(codecs.encode(rot13, 'rot_13')) # Salom (qaytadi)
# Yoki qo'lda:
def rot13(text):
return caesar_encrypt(text, 13)
Frekvens tahlil
Ingliz tilida harflar bir xil chastota bilan uchraydi. E eng ko'p (~13%), keyin T, A, O, I...
from collections import Counter
def frequency_analysis(ciphertext: str) -> dict:
letters = [c for c in ciphertext.upper() if c.isalpha()]
total = len(letters)
freq = Counter(letters)
return {k: v/total*100 for k, v in sorted(freq.items(), key=lambda x: -x[1])}
# Eng ko'p uchraydigan harf E ga mos kelishi kerak
ct_freq = frequency_analysis("QXOO{fdhvdu_flskhu_lv_rog}")
print(ct_freq)
💡 Bu mavzu bo'yicha amaliy mashq qilishni istaysizmi?
Klassik challengelarini ko'rish →