XOR Operatsiyasi
Simmetrik
Oson
XOR (Eksklyuziv OR) nima?
XOR — ikki bitni taqqoslaydigan mantiqiy operatsiya. Faqat bittasi 1 bo'lganda natija 1.
| A | B | A XOR B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
XOR ning muhim xususiyatlari
- A XOR A = 0 — o'zi bilan XOR → 0
- A XOR 0 = A — nol bilan XOR → o'zgarmaydi
- A XOR B = B XOR A — kommutativ
- (A XOR B) XOR B = A — bu kriptografiya uchun muhim!
Qanday shifrlaydi?
# XOR shifrlash
def xor_encrypt(plaintext, key):
# Kalit takrorlanadi (cycling)
result = []
for i, char in enumerate(plaintext):
encrypted_byte = ord(char) ^ ord(key[i % len(key)])
result.append(chr(encrypted_byte))
return ''.join(result)
def xor_decrypt(ciphertext, key):
# XOR o'zi o'zining teskarisi!
return xor_encrypt(ciphertext, key)
# Misol
matn = "Salom"
kalit = "K"
encrypted = ''.join(chr(ord(c) ^ ord(kalit)) for c in matn)
print("Shifrlangan:", encrypted)
decrypted = ''.join(chr(ord(c) ^ ord(kalit)) for c in encrypted)
print("Deshifrlangan:", decrypted) # Salom
Python bytes bilan
# Hex ma'lumot bilan ishlash
ciphertext_hex = "1c 37 36 36 71"
key_byte = 0x42
ciphertext = bytes.fromhex(ciphertext_hex.replace(' ', ''))
plaintext = bytes([b ^ key_byte for b in ciphertext])
print(plaintext.decode('utf-8', errors='replace'))
# Ko'p baytli kalit bilan
def xor_bytes(data: bytes, key: bytes) -> bytes:
return bytes([data[i] ^ key[i % len(key)] for i in range(len(data))])
data = b"\x9d\xc4\xc5\xc1"
key = b"KEY"
result = xor_bytes(data, key)
print(result)
Single-byte XOR ni qanday buzish mumkin?
1
Flag har doim NULL{ bilan boshlanadi
2
Birinchi bayt: N = 78 (ASCII)
3
kalit = ct[0] XOR 78
4
Barcha baytlarga shu kalit bilan XOR qiling
# Single-byte XOR cracking
def crack_single_xor(ciphertext: bytes) -> tuple:
# Eng yaxshi kalitni qidirish (ingliz matni bo'lsa)
best_key = 0
best_score = 0
english_freqs = "etaoinshrdlu" # Eng ko'p uchraydigan harflar
for key in range(256):
decrypted = bytes([b ^ key for b in ciphertext])
try:
text = decrypted.decode('utf-8')
score = sum(1 for c in text.lower() if c in english_freqs)
if score > best_score:
best_score = score
best_key = key
except:
continue
return best_key, bytes([b ^ best_key for b in ciphertext])
ct = bytes.fromhex("2b0e0b0b5c7976...")
key, pt = crack_single_xor(ct)
print(f"Kalit: {key} (0x{key:02x})")
print(f"Plaintext: {pt}")
💡 Bu mavzu bo'yicha amaliy mashq qilishni istaysizmi?
Simmetrik challengelarini ko'rish →