Kodax

أمن كلمات المرور — أساسيات الأمن السيبراني

أمن كلمات المرور

خصائص كلمة المرور القوية

- 12 حرف على الأقل

- أحرف كبيرة وصغيرة

- أرقام ورموز

- لا معلومات شخصية

- فريدة لكل حساب

هجمات كلمات المرور

🔨 Brute Force

تجربة كل الاحتمالات.

📖 Dictionary Attack

استخدام قائمة كلمات شائعة.

🌈 Rainbow Table

جداول محسوبة مسبقاً للـ hashes.

🎭 Credential Stuffing

استخدام بيانات مسربة.

أفضل الممارسات

- استخدم Password Manager

- فعّل 2FA/MFA

- لا تعيد استخدام كلمات المرور

- غيّرها عند الاختراق

import secrets
import string
import hashlib
import hmac

class PasswordManager:
    """
    أدوات إدارة كلمات المرور الآمنة
    """
    
    @staticmethod
    def generate_password(length=16, 
                         use_upper=True, 
                         use_lower=True,
                         use_digits=True, 
                         use_special=True):
        """
        توليد كلمة مرور عشوائية آمنة
        """
        characters = ""
        required = []
        
        if use_lower:
            characters += string.ascii_lowercase
            required.append(secrets.choice(string.ascii_lowercase))
        
        if use_upper:
            characters += string.ascii_uppercase
            required.append(secrets.choice(string.ascii_uppercase))
        
        if use_digits:
            characters += string.digits
            required.append(secrets.choice(string.digits))
        
        if use_special:
            special = "!@#$%^&*()_+-=[]{}|;:,.<>?"
            characters += special
            required.append(secrets.choice(special))
        
        # توليد باقي الأحرف
        remaining_length = length - len(required)
        password_chars = required + [
            secrets.choice(characters) 
            for _ in range(remaining_length)
        ]
        
        # خلط الأحرف
        secrets.SystemRandom().shuffle(password_chars)
        
        return ''.join(password_chars)
    
    @staticmethod
    def generate_passphrase(num_words=4):
        """
        توليد عبارة مرور (أسهل للحفظ)
        """
        # قائمة كلمات بسيطة (في الواقع استخدم قائمة أكبر)
        words = [
            "apple", "banana", "cherry", "dragon", "eagle",
            "forest", "galaxy", "harbor", "island", "jungle",
            "knight", "lemon", "mountain", "nebula", "ocean",
            "phoenix", "quantum", "river", "storm", "thunder",
            "umbrella", "volcano", "winter", "xenon", "yellow"
        ]
        
        selected = [secrets.choice(words) for _ in range(num_words)]
        separator = secrets.choice(["-", "_", "."])
        
        return separator.join(selected)
    
    @staticmethod
    def hash_password(password, salt=None):
        """
        تشفير كلمة المرور (للتخزين)
        """
        if salt is None:
            salt = secrets.token_hex(16)
        
        # استخدام PBKDF2 (أفضل من MD5/SHA1)
        hash_value = hashlib.pbkdf2_hmac(
            'sha256',
            password.encode('utf-8'),
            salt.encode('utf-8'),
            600_000  # iterations (توصية OWASP الحالية لـ PBKDF2-SHA256)
        )
        
        return {
            "salt": salt,
            "hash": hash_value.hex()
        }
    
    @staticmethod
    def verify_password(password, salt, stored_hash):
        """
        التحقق من كلمة المرور
        """
        hash_value = hashlib.pbkdf2_hmac(
            'sha256',
            password.encode('utf-8'),
            salt.encode('utf-8'),
            600_000
        )
        # مقارنة ثابتة الزمن: == قد تكشف عبر التوقيت عدد الأحرف المتطابقة
        return hmac.compare_digest(hash_value.hex(), stored_hash)
    
    @staticmethod
    def check_pwned(password):
        """
        فحص إذا كانت كلمة المرور مسربة
        (باستخدام k-anonymity - آمن)
        """
        sha1 = hashlib.sha1(password.encode('utf-8')).hexdigest().upper()
        prefix = sha1[:5]
        suffix = sha1[5:]
        
        # في التطبيق الحقيقي: ارسل prefix لـ haveibeenpwned API
        # هنا نحاكي النتيجة
        return {
            "prefix": prefix,
            "is_pwned": False,  # محاكاة
            "message": "للفحص الحقيقي استخدم haveibeenpwned.com/Passwords"
        }

# اختبار
pm = PasswordManager()

# توليد كلمات مرور
print("كلمة مرور عشوائية:")
print(pm.generate_password(16))

print("\nعبارة مرور:")
print(pm.generate_passphrase(4))

# تشفير والتحقق
password = "MySecureP@ss123"
hashed = pm.hash_password(password)
print(f"\nSalt: {hashed['salt']}")
print(f"Hash: {hashed['hash'][:40]}...")

# التحقق
is_valid = pm.verify_password(password, hashed['salt'], hashed['hash'])
print(f"\nالتحقق: {'✅ صحيحة' if is_valid else '❌ خاطئة'}")
اختبر فهمك