Skip to main content

Firen - A modern educational block cipher

Project description

Firen - Modern Block Cipher

Firen is a high-security, educational block cipher designed to demonstrate modern cryptographic principles while maintaining production-grade code quality. It is implemented entirely in Python from scratch, without relying on existing cryptographic libraries.

⚠️ Educational Use Only

IMPORTANT: Firen is designed for educational purposes only. It has not undergone formal cryptographic analysis or security auditing. For production systems requiring encryption, use well-established, audited libraries like OpenSSL, libsodium, or the cryptography package.

Features

  • Modern Design: Substitution-Permutation Network (SPN) architecture
  • Large Block Size: 256-bit (default) or 512-bit blocks
  • Strong Key: 512-bit master key
  • Configurable Rounds: 20-32 rounds (default 24)
  • Strong Diffusion: Optimized S-box and P-box for avalanche effect
  • Secure Key Schedule: Resistant to related-key and slide attacks
  • Multiple Modes:
    • CTR (Counter) mode for stream encryption
    • XTS mode for disk encryption
    • GCM-like AEAD for authenticated encryption
  • Side-Channel Protection: Constant-time operations
  • Clean Architecture: Modular, production-ready code structure

Installation

# Clone the repository
git clone <repository-url>
cd PythonProject2

# No external dependencies required - pure Python
python -m firen

Quick Start

Basic Block Encryption

from firen import FirenCipher
from firen.core.constants import BLOCK_SIZE_256, KEY_SIZE

# Generate a 512-bit key (64 bytes)
key = bytes(range(KEY_SIZE))

# Initialize cipher with 256-bit blocks and 24 rounds
cipher = FirenCipher(key, rounds=24, block_size=BLOCK_SIZE_256)

# Encrypt a block
plaintext = bytes(BLOCK_SIZE_256)  # 32 bytes for 256-bit block
ciphertext = cipher.encrypt_block(plaintext)

# Decrypt the block
decrypted = cipher.decrypt_block(ciphertext)
assert decrypted == plaintext

CTR Mode (Stream Encryption)

from firen.core.cipher import FirenCipher
from firen.modes.ctr import CTRMode
from firen.core.constants import KEY_SIZE, BLOCK_SIZE_256

key = bytes(range(KEY_SIZE))
cipher = FirenCipher(key, block_size=BLOCK_SIZE_256)
nonce = bytes(BLOCK_SIZE_256)  # Must be unique for each encryption

ctr = CTRMode(cipher, nonce)
plaintext = b"Hello, World! This is a secret message."

ciphertext = ctr.encrypt(plaintext)
decrypted = ctr.decrypt(ciphertext)

assert decrypted == plaintext

XTS Mode (Disk Encryption)

from firen.modes.xts import XTSMode
from firen.core.constants import KEY_SIZE

# Two keys for XTS: data key and tweak key
data_key = bytes(range(KEY_SIZE))
tweak_key = bytes([x ^ 0xFF for x in range(KEY_SIZE)])

xts = XTSMode(data_key, tweak_key)

# Encrypt a sector (e.g., 4096 bytes)
sector = bytes(4096)
sector_number = 0

encrypted_sector = xts.encrypt_sector(sector, sector_number)
decrypted_sector = xts.decrypt_sector(encrypted_sector, sector_number)

assert decrypted_sector == sector

AEAD (Authenticated Encryption)

from firen.aead.firen_gcm import FirenGCM
from firen.core.constants import KEY_SIZE

key = bytes(range(KEY_SIZE))
nonce = b"unique_nonce_12"  # 12 bytes recommended

gcm = FirenGCM(key, nonce)

plaintext = b"Secret message"
associated_data = b"Metadata: user_id=12345"

# Encrypt with authentication
ciphertext, tag = gcm.encrypt(plaintext, associated_data)

# Decrypt and verify
try:
    decrypted = gcm.decrypt(ciphertext, tag, associated_data)
    print("Decryption successful:", decrypted)
except ValueError:
    print("Authentication failed!")

Architecture

Project Structure

firen/
├── __init__.py              # Package initialization
├── core/                    # Core cipher implementation
│   ├── __init__.py
│   ├── cipher.py           # Main Firen cipher
│   ├── constants.py        # Cryptographic constants
│   ├── sbox.py             # S-box (substitution)
│   ├── pbox.py             # P-box (permutation)
│   └── key_schedule.py     # Key schedule algorithm
├── modes/                   # Modes of operation
│   ├── __init__.py
│   ├── ctr.py              # CTR mode
│   └── xts.py              # XTS mode
├── aead/                    # Authenticated encryption
│   ├── __init__.py
│   └── firen_gcm.py        # GCM-like AEAD
└── utils/                   # Utility functions
    ├── __init__.py
    ├── constant_time.py    # Side-channel protection
    └── conversion.py       # Data conversion utilities

tests/                        # Comprehensive test suite
├── test_cipher.py
├── test_key_schedule.py
├── test_sbox_pbox.py
├── test_modes.py
├── test_aead.py
├── test_utils.py
└── run_all_tests.py

Cipher Design

Block Structure

Firen uses a Substitution-Permutation Network (SPN) with:

  • Block Size: 256 bits (32 bytes) or 512 bits (64 bytes)
  • Key Size: 512 bits (64 bytes)
  • Word Size: 64 bits (8 bytes)
  • Rounds: 24 (configurable 20-32)

Round Function

Each round consists of:

  1. SubBytes: S-box substitution for non-linearity
  2. ShiftRows: Word rotation for diffusion
  3. MixColumns: Linear transformation using MDS-like matrix
  4. AddRoundKey: XOR with round subkey

The final round omits MixColumns for efficiency.

Key Schedule

The key schedule generates round subkeys with:

  • Word Rotation: Diffusion across key words
  • S-box Substitution: Non-linear transformation
  • Round Constants: LFSR-based unique constants per round
  • XOR Mixing: Avalanche effect between key words

This design provides resistance to:

  • Related-key attacks
  • Slide attacks
  • Key recovery attacks

S-box

The 8-bit S-box is designed for:

  • High non-linearity
  • Low differential uniformity
  • High algebraic degree
  • Resistance to linear cryptanalysis

P-box

The permutation provides:

  • Bit diffusion across the block
  • Avalanche effect maximization
  • Efficient implementation

Security Considerations

Strengths

  • Large Block Size: 256/512 bits provides resistance to birthday attacks
  • Strong Key Schedule: Resistant to related-key and slide attacks
  • Multiple Rounds: 24 rounds provide large security margin
  • Constant-Time: Side-channel attack protection

Limitations

  • Pure Python: Not optimized for performance
  • Unaudited: No formal security analysis
  • Educational: Not for production use

Recommended Usage

  • Educational: Learning cryptography concepts
  • Research: Testing new cryptographic ideas
  • Prototyping: Developing new modes of operation

Testing

Run the comprehensive test suite:

python tests/run_all_tests.py

Or run individual test files:

python -m unittest tests.test_cipher
python -m unittest tests.test_modes
python -m unittest tests.test_aead

Performance

Firen is implemented in pure Python for clarity and educational value. Performance characteristics:

  • Block Encryption: ~1-5 ms per block (depending on rounds)
  • CTR Mode: Stream encryption, parallelizable
  • XTS Mode: Sector encryption, suitable for disk I/O

For production performance, consider:

  • PyPy interpreter
  • Cython compilation
  • C/C++ extensions

API Reference### FirenCipher

class FirenCipher:
    def __init__(self, key: bytes, rounds: int = 24, block_size: int = 32)
    def encrypt_block(self, plaintext: bytes) -> bytes
    def decrypt_block(self, ciphertext: bytes) -> bytes
    def encrypt(self, plaintext: bytes) -> bytes  # ECB mode
    def decrypt(self, ciphertext: bytes) -> bytes  # ECB mode

CTRMode

class CTRMode:
    def __init__(self, cipher: FirenCipher, nonce: bytes)
    def encrypt(self, plaintext: bytes) -> bytes
    def decrypt(self, ciphertext: bytes) -> bytes
    def reset(self) -> None
    def set_counter(self, value: int) -> None

XTSMode

class XTSMode:
    def __init__(self, data_key: bytes, tweak_key: bytes, block_size: int = 32)
    def encrypt_sector(self, data: bytes, sector_number: int) -> bytes
    def decrypt_sector(self, data: bytes, sector_number: int) -> bytes

FirenGCM

class FirenGCM:
    def __init__(self, key: bytes, nonce: bytes, block_size: int = 32)
    def encrypt(self, plaintext: bytes, associated_data: bytes = b"") -> tuple[bytes, bytes]
    def decrypt(self, ciphertext: bytes, tag: bytes, associated_data: bytes = b"") -> bytes

Contributing

Contributions are welcome! Areas of interest:

  • Performance optimizations
  • Additional modes of operation
  • Security analysis
  • Documentation improvements
  • Test coverage expansion

License

This project is provided for educational purposes. See LICENSE file for details.

Disclaimer

Firen is an educational cryptographic project. It has not undergone formal security auditing. Do not use it in production systems or for protecting sensitive data. For production encryption, use well-established, audited cryptographic libraries.

References

  • "The Design of Rijndael" by Joan Daemen and Vincent Rijmen
  • "Cryptography Engineering" by Niels Ferguson, Bruce Schneier, and Tadayoshi Kohno
  • NIST Special Publication 800-38A (Recommendation for Block Cipher Modes of Operation)
  • NIST Special Publication 800-38D (Recommendation for Galois/Counter Mode)

Contact

For questions, issues, or contributions, please open an issue on the project repository.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

firen-1.0.1.tar.gz (34.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

firen-1.0.1-py3-none-any.whl (23.9 kB view details)

Uploaded Python 3

File details

Details for the file firen-1.0.1.tar.gz.

File metadata

  • Download URL: firen-1.0.1.tar.gz
  • Upload date:
  • Size: 34.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for firen-1.0.1.tar.gz
Algorithm Hash digest
SHA256 43e024e22618c10a1176fe6683b4252dca2130138ecdc6b60ef7dbff59d7f887
MD5 c03f3de45cb4f9cb15ed9a6a8de8cbbf
BLAKE2b-256 007d419659c9972738d15dacef56f313562d5fd3abf6495ae34324e93e3fea6f

See more details on using hashes here.

File details

Details for the file firen-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: firen-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 23.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for firen-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 db58ec98372a3c1039c4d1c187a3d136592f71fc47dbaffe280fa6af504821a3
MD5 598998eb4a18a10790c8f8a5c460f77a
BLAKE2b-256 672cfd592ad0ee34f4c4b6af7b3dd3f04835506f8b33b995bff4293c5a5f9dd0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page