التشفير الأساسي — أساسيات الأمن السيبراني
التشفير (Cryptography)
أنواع التشفير
التشفير المتماثل (Symmetric)
- مفتاح واحد للتشفير والفك
- أسرع
- أمثلة: AES, DES
التشفير غير المتماثل (Asymmetric)
- مفتاح عام للتشفير
- مفتاح خاص للفك
- أمثلة: RSA, ECC
Hashing
- اتجاه واحد (لا يُفك)
- للتحقق من السلامة
- أمثلة: SHA-256, bcrypt
استخدامات التشفير
- 🔐 حماية البيانات
- 🌐 HTTPS/TLS
- 📧 توقيع البريد
- 💰 العملات الرقمية
- 🔑 كلمات المرور
import hashlib
import base64
import os
from typing import Tuple
class CryptoDemo:
"""
عرض توضيحي لمفاهيم التشفير
⚠️ للتعليم فقط - في الإنتاج استخدم مكتبات موثوقة
"""
# ===== Caesar Cipher (تاريخي - للتعليم) =====
@staticmethod
def caesar_encrypt(text, shift=3):
"""تشفير قيصر البسيط"""
result = ""
for char in text:
if char.isalpha():
ascii_offset = ord('A') if char.isupper() else ord('a')
shifted = (ord(char) - ascii_offset + shift) % 26
result += chr(shifted + ascii_offset)
else:
result += char
return result
@staticmethod
def caesar_decrypt(text, shift=3):
"""فك تشفير قيصر"""
return CryptoDemo.caesar_encrypt(text, -shift)
# ===== XOR Cipher =====
@staticmethod
def xor_cipher(data: bytes, key: bytes) -> bytes:
"""تشفير XOR البسيط"""
return bytes([d ^ key[i % len(key)] for i, d in enumerate(data)])
# ===== Hashing =====
@staticmethod
def hash_md5(data: str) -> str:
"""MD5 hash (⚠️ ضعيف - لا تستخدم للأمان)"""
return hashlib.md5(data.encode()).hexdigest()
@staticmethod
def hash_sha256(data: str) -> str:
"""SHA-256 hash (آمن)"""
return hashlib.sha256(data.encode()).hexdigest()
@staticmethod
def hash_sha512(data: str) -> str:
"""SHA-512 hash (أقوى)"""
return hashlib.sha512(data.encode()).hexdigest()
@staticmethod
def hash_with_salt(password: str, salt: bytes = None) -> Tuple[str, bytes]:
"""Hash مع salt"""
if salt is None:
salt = os.urandom(16)
hash_value = hashlib.pbkdf2_hmac(
'sha256',
password.encode(),
salt,
600_000 # توصية OWASP الحالية
)
return hash_value.hex(), salt
# ===== Base64 (ترميز وليس تشفير!) =====
@staticmethod
def base64_encode(data: str) -> str:
"""ترميز Base64 (ليس تشفير!)"""
return base64.b64encode(data.encode()).decode()
@staticmethod
def base64_decode(data: str) -> str:
"""فك ترميز Base64"""
return base64.b64decode(data.encode()).decode()
# ===== أدوات تحليل =====
@staticmethod
def frequency_analysis(text: str) -> dict:
"""تحليل التردد (لكسر التشفير البسيط)"""
text = text.upper()
freq = {}
total = 0
for char in text:
if char.isalpha():
freq[char] = freq.get(char, 0) + 1
total += 1
# تحويل لنسب مئوية
for char in freq:
freq[char] = round((freq[char] / total) * 100, 2)
return dict(sorted(freq.items(), key=lambda x: x[1], reverse=True))
# ===== أمثلة =====
crypto = CryptoDemo()
# Caesar Cipher
print("=== Caesar Cipher ===")
original = "HELLO WORLD"
encrypted = crypto.caesar_encrypt(original, 3)
decrypted = crypto.caesar_decrypt(encrypted, 3)
print(f"Original: {original}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
# Hashing
print("\n=== Hashing ===")
message = "password123"
print(f"النص: {message}")
print(f"MD5: {crypto.hash_md5(message)}")
print(f"SHA256: {crypto.hash_sha256(message)}")
# Hash مع Salt
print("\n=== Hash with Salt ===")
hash_val, salt = crypto.hash_with_salt("mypassword")
print(f"Hash: {hash_val[:40]}...")
print(f"Salt: {salt.hex()}")
# Base64
print("\n=== Base64 (ترميز وليس تشفير!) ===")
text = "Secret Message"
encoded = crypto.base64_encode(text)
decoded = crypto.base64_decode(encoded)
print(f"Original: {text}")
print(f"Encoded: {encoded}")
print(f"Decoded: {decoded}")
# Frequency Analysis
print("\n=== Frequency Analysis ===")
sample = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
freq = crypto.frequency_analysis(sample)
print("أكثر 5 حروف تكراراً:")
for i, (char, pct) in enumerate(list(freq.items())[:5]):
print(f" {char}: {pct}%")اختبر فهمك