Skip to content

mattsebastianh/encryption_testing

Repository files navigation

Encryption Security Testing Project

Table of Contents

Project Overview

This project is a security testing framework designed to evaluate and identify vulnerabilities in cryptographic implementations. It focuses on testing AES encryption implementations to uncover common security flaws such as weak keys, improper IV usage, and hardcoded cryptographic materials.

The project demonstrates how seemingly functional encryption code can contain critical security vulnerabilities that render the encryption ineffective or easily breakable.

Objectives and Goals

Primary Objectives

  • Security Assessment: Evaluate the security posture of encryption implementations
  • Vulnerability Detection: Identify common cryptographic implementation flaws
  • Educational Purpose: Demonstrate security testing methodologies for encryption code
  • Best Practice Validation: Verify adherence to cryptographic best practices

Specific Goals

  • Test key and IV length compliance with AES requirements
  • Validate proper randomization of cryptographic parameters
  • Ensure encryption/decryption functionality integrity
  • Identify hardcoded or weak cryptographic materials
  • Provide actionable security recommendations

Project Structure

encryption_testing/
├── README.md              # This documentation file
├── LICENSE                # Project license
├── encryption.py          # AES encryption implementation (INSECURE - for testing)
└── encryption_test.py     # Security test suite

File Descriptions

  • encryption.py: Contains a deliberately insecure AES encryption implementation with multiple security flaws
  • encryption_test.py: Comprehensive test suite that validates cryptographic parameters and functionality
  • README.md: Project documentation and security analysis
  • LICENSE: Project licensing information

Security Findings

⚠️ CRITICAL SECURITY ISSUES DETECTED ⚠️

The current implementation has 5 critical security vulnerabilities:

Test Case Status Issue
Key Length Test FAILED Key is 11 bytes (88 bits) instead of required 16+ bytes
IV Length Test FAILED IV is 10 bytes (80 bits) instead of required 16 bytes
Encryption Test ERROR Encryption fails due to invalid key size
Different Data Test ERROR Cannot encrypt due to key size violation
IV Randomness Test ERROR Static IV prevents proper security testing

Installation

Prerequisites

  • Python 3.7+
  • pip or conda package manager

Setup Instructions

  1. Clone or download the project

    cd /path/to/your/workspace
  2. Install required dependencies

    # Using conda (recommended)
    conda install cryptography -y
    
    # Or using pip
    pip install cryptography
  3. Verify installation

    python -c "from cryptography.hazmat.primitives.ciphers import Cipher; print('Cryptography installed successfully')"

Test Usage

Running Security Tests

Basic Test Execution

# Run all security tests
python encryption_test.py

# Run with verbose output
python -v encryption_test.py

Using unittest module

# Run specific test method
python -m unittest encryption_test.TestEncryptionDecryption.test_key_length

# Run with discovery
python -m unittest discover -s . -p "*test*.py"

Expected Output

When running the tests on the current insecure implementation:

EEFEF
======================================================================
ERROR: Multiple tests fail due to invalid key size (88) for AES
FAIL: Key length (11 bytes) != required (16 bytes)  
FAIL: IV length (10 bytes) != required (16 bytes)
======================================================================
Ran 5 tests in 0.006s
FAILED (failures=2, errors=3)

Test Case Descriptions

Test Method Purpose Expected Behavior
test_key_length() Validates AES key size requirements Should verify 16+ byte keys
test_iv_length() Validates IV size for AES-CBC Should verify 16-byte IVs
test_encrypt_decrypt() Tests basic encryption roundtrip Should encrypt and decrypt successfully
test_encrypt_decrypt_different_data() Tests multiple data encryption Should handle different inputs correctly
test_iv_randomness() Validates IV uniqueness Should produce different ciphertexts for same plaintext

Security Vulnerabilities Identified

1. Invalid Key Size 🔴 Critical

  • Issue: Key is 11 bytes (88 bits) instead of minimum 16 bytes (128 bits)
  • Impact: Extremely weak encryption, vulnerable to brute force attacks
  • Current: b'insecurekey'
  • Required: Minimum 16 bytes for AES-128, 32 bytes recommended for AES-256

2. Invalid IV Size 🔴 Critical

  • Issue: IV is 10 bytes instead of required 16 bytes for AES block size
  • Impact: Encryption algorithm cannot function properly
  • Current: b'insecureiv'
  • Required: Exactly 16 bytes for AES-CBC mode

3. Hardcoded Cryptographic Materials 🔴 Critical

  • Issue: Both key and IV are hardcoded in source code
  • Impact: No security - anyone with code access knows the key
  • Solution: Generate cryptographically secure random keys and IVs

4. Static IV Usage 🔴 Critical

  • Issue: Same IV used for all encryptions
  • Impact: Same plaintext produces same ciphertext (pattern leakage)
  • Solution: Generate unique IV for each encryption operation

5. No Key Management 🟠 High

  • Issue: No secure key storage or derivation mechanisms
  • Impact: Keys exposed in memory and source code
  • Solution: Implement proper key derivation and storage

Recommended Fixes

Immediate Security Fixes

# SECURE implementation example
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend

def generate_key_from_password(password: bytes, salt: bytes) -> bytes:
    """Generate a secure key from password using PBKDF2"""
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,  # 256-bit key
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    return kdf.derive(password)

def encrypt_secure(data: bytes, password: bytes) -> tuple:
    """Secure encryption with random IV and proper key derivation"""
    salt = os.urandom(16)  # Random salt
    iv = os.urandom(16)    # Random IV for each encryption
    key = generate_key_from_password(password, salt)
    
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    
    # Add padding if necessary
    padded_data = pad_data(data)
    ciphertext = encryptor.update(padded_data) + encryptor.finalize()
    
    return ciphertext, salt, iv

Security Testing Improvements

  1. Add entropy testing for key and IV generation
  2. Implement timing attack resistance testing
  3. Add key derivation function validation
  4. Test multiple encryption operations with same key
  5. Validate proper padding implementation

Best Practices

Cryptographic Implementation

  • ✅ Use cryptographically secure random number generators
  • ✅ Generate unique IVs for each encryption operation
  • ✅ Use proper key sizes (256-bit recommended)
  • ✅ Implement secure key derivation functions
  • ✅ Never hardcode cryptographic materials
  • ✅ Use authenticated encryption modes (AES-GCM recommended)

Security Testing

  • ✅ Test all cryptographic parameter requirements
  • ✅ Validate randomness and uniqueness of generated values
  • ✅ Test edge cases and error conditions
  • ✅ Implement automated security regression testing
  • ✅ Regular security audits and penetration testing

Development Workflow

  • ✅ Security testing in CI/CD pipeline
  • ✅ Code review for cryptographic implementations
  • ✅ Regular dependency security scanning
  • ✅ Documentation of security assumptions and requirements

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/security-improvement)
  3. Make your changes and add tests
  4. Run the security test suite
  5. Commit your changes (git commit -am 'Add security improvement')
  6. Push to the branch (git push origin feature/security-improvement)
  7. Create a Pull Request

Security Contributions Welcome

  • Additional test cases for cryptographic validation
  • Secure implementation examples
  • Documentation improvements
  • Security analysis tools integration

License

This project is licensed under the terms specified in the LICENSE file.


⚠️ SECURITY WARNING: The encryption implementation in this project contains deliberate security vulnerabilities for educational and testing purposes. DO NOT USE the current encryption.py implementation in production systems.

For questions about security testing or to report additional vulnerabilities, please create an issue in the project repository.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages