Metadata-Version: 2.4
Name: eb47ns
Version: 0.3.0
Summary: Ethiopian Base-47 Numeral System (EB47NS) with Direct Digit Arithmetic and Ethiopian Cryptographic System (ECS)
Author-email: Ezra Destaw <ezradestaw@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/Ezradestaw/eb47
Project-URL: Repository, https://github.com/Ezradestaw/eb47
Project-URL: Issues, https://github.com/Ezradestaw/eb47/issues
Keywords: numeral-system,base-47,arithmetic,cryptography,ecs,galois-field,symmetric-encryption
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Security :: Cryptography
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Dynamic: license-file

# Ethiopian Base-47 Numeral System (EB47NS) & Ethiopian Cryptographic System (ECS)

[![PyPI Version](https://img.shields.io/pypi/v/eb47ns.svg)](https://pypi.org/project/eb47ns/)
[![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![Tests](https://img.shields.io/badge/tests-204%20passed-brightgreen.svg)]()
[![GitHub](https://img.shields.io/badge/github-Ezradestaw%2FEb47-blue?logo=github)](https://github.com/Ezradestaw/eb47)

> [!WARNING]
> **CRITICAL SCIENTIFIC & SECURITY NOTICE:**  
> **ECS (Ethiopian Cryptographic System)** is an experimental cryptographic construction and has not undergone independent cryptanalysis, peer review, or standardization. It must **not** be used to protect sensitive or production data.
>
> This project does **NOT** claim military-grade security, bank-grade security, unbreakable encryption, proven security, or superiority over AES, RSA, or standardized symmetric ciphers. It is presented strictly as a research and educational implementation exploring non-binary algebraic structures, prime radix representations, and custom block cipher models.

---

## Table of Contents

1. [Project Name & Overview](#1-project-name--overview)
2. [Description & Architectural Stack](#2-description--architectural-stack)
3. [Installation](#3-installation)
4. [Quick-Start Example](#4-quick-start-example)
5. [Base47 Specification & Alphabet](#5-base47-specification--alphabet)
6. [ECS Architecture](#6-ecs-architecture)
7. [Message Preprocessing](#7-message-preprocessing)
8. [Fibonacci Padding](#8-fibonacci-padding)
9. [SHA-256 Key Preprocessing](#9-sha-256-key-preprocessing)
10. [127-Bit Message Block Specification](#10-127-bit-message-block-specification)
11. [127/128-Bit Domain Separation](#11-127128-bit-domain-separation)
12. [Base47 Conversion & Leading Zero Preservation](#12-base47-conversion--leading-zero-preservation)
13. [Matrix Transformation Layer](#13-matrix-transformation-layer)
14. [Key Matrix Generation & Inversion](#14-key-matrix-generation--inversion)
15. [Encryption Algorithm & Pseudocode](#15-encryption-algorithm--pseudocode)
16. [Decryption Algorithm & Pseudocode](#16-decryption-algorithm--pseudocode)
17. [Explicit Overflow Behavior](#17-explicit-overflow-behavior)
18. [Ciphertext Wire Format](#18-ciphertext-wire-format)
19. [Mathematical Notation](#19-mathematical-notation)
20. [Security Limitations & Non-Claims](#20-security-limitations--non-claims)
21. [Complete Code Examples & CLI](#21-complete-code-examples--cli)
22. [Automated Testing & Test Vectors](#22-automated-testing--test-vectors)
23. [Development Instructions](#23-development-instructions)
24. [License](#24-license)
25. [PyPI & TestPyPI Publication Instructions](#25-pypi--testpypi-publication-instructions)

---

## 1. Project Name & Overview

* **Repository:** `Ezradestaw/eb47` & `Ezradestaw/ECS`
* **Distribution Package:** `eb47ns` (v0.3.0)
* **Primary Python Modules:** `eb47ns` (Base-47 Arithmetic Engine) and `ecs` (Ethiopian Cryptographic System)
* **Author:** Ezra Destaw (<ezradestaw@gmail.com>)

EB47NS provides a rigorous radix-47 numeral architecture with direct digit arithmetic, abstract ring operations, and Galois field algebra. ECS builds on top of EB47NS as an experimental symmetric block cipher operating on **127-bit message blocks**, **128-bit key material**, and **4×4 invertible key matrices over $\mathbb{F}_{47}$**.

---

## 2. Description & Architectural Stack

```text
                                RADIX-47
                                   │
     ┌─────────────────────────────┼─────────────────────────────┐
     │                             │                             │
Representation                Arithmetic                   Number Theory
     │                             │                             │
  Alphabet & Bijections        + - × ÷ (Direct Digits)       GCD / LCM / ExtGCD
  Encoding / Decoding          % pow                         Modular Inv / Add / Mul
  Bytes Transformations        Successor / Predecessor       isqrt / Miller-Rabin
     │                             │                             │
     └─────────────────────────────┼─────────────────────────────┘
                                   │
                    Polynomial Ring & Linear Algebra
                                   │
              ┌────────────────────┴────────────────────┐
              │                                         │
        Polynomials F_47[x]                       Matrices M_nxn(F_47)
              │                                         │
         Add / Sub / Mul / Div                     Add / Mul / Exponentiation
         Lagrange Interpolation                    Gauss-Jordan Inversion
              │                                         │
              └────────────────────┬────────────────────┘
                                   │
                     ECS Cryptographic Layer (v0.1.0)
                                   │
     ┌─────────────────────────────┼─────────────────────────────┐
     │                             │                             │
Message Processing           Key Material                  Diffusion Layer
     │                             │                             │
  32-bit Length Header         SHA-256 Key Preprocessing     4x4 Invertible KeyMatrix
  Fibonacci Padding            128-bit Material (H0 ^ H1)    A x x = B over F_47
  Strict 127-bit Boundary      Key Matrix Synthesis          CBC XOR Chaining
```

---

## 3. Installation

From PyPI:
```bash
pip install eb47ns
```

From source:
```bash
git clone https://github.com/Ezradestaw/eb47.git
cd eb47
pip install -e .
```

---

## 4. Quick-Start Example

### Python API

```python
from ecs import ECS, encrypt, decrypt

# 1. Initialize cipher with user key
cipher = ECS("my_secret_key_12345")

# 2. Encrypt arbitrary binary or text data
message = b"Confidential experimental message payload!"
ciphertext = cipher.encrypt(message)
print("Ciphertext:", ciphertext)
# Output: ECS1:2:762FCgIbCdqrfj...:aljd5vixr

# 3. Decrypt back to original bytes
recovered = cipher.decrypt(ciphertext)
assert recovered == message
print("Recovered:", recovered.decode("utf-8"))

# Functional one-liner interface
ct = encrypt(b"Hello World", "secret")
pt = decrypt(ct, "secret")
assert pt == b"Hello World"
```

### Command Line Interface (CLI)

```bash
# Encrypt message
ecs encrypt -k "my_secret" -m "Hello from CLI"

# Decrypt message
ecs decrypt -k "my_secret" -c "ECS1:1:...:..."

# System information
ecs info
```

---

## 5. Base47 Specification & Alphabet

The intended alphabet consists of **exactly 47 unique ASCII symbols** in strict positional order:

```text
0abcdefghijklmnopqrstuvwxyz123456789!$?BCDEFGHI
```

### Alphabet Partition:
1. **Index 0:** `'0'` (null symbol)
2. **Indices 1–26:** `'a'` through `'z'` (26 lowercase Latin glyphs)
3. **Indices 27–35:** `'1'` through `'9'` (9 decimal digit glyphs)
4. **Indices 36–38:** `'!'`, `'$'`, `'?'` (3 punctuation glyphs)
5. **Indices 39–46:** `'B'` through `'I'` (8 uppercase Latin glyphs)

*Note: Glyphs `'A'` and `'J'` through `'Z'` are absent.*

Every digit value satisfies:
$$0 \le d < 47$$

---

## 6. ECS Architecture

ECS is structured as a sequential block cipher:
1. **Message Preprocessing:** Prepends a 32-bit length header, appends message bits, and pads with a deterministic Fibonacci bit sequence to reach exact multiples of **127 bits**.
2. **Key Derivation:** Hashes the user key with **SHA-256** and folds the 256-bit digest into **128-bit key material**.
3. **Key Matrix Synthesis:** Generates an invertible $4 \times 4$ key matrix $A$ over Galois Field $\mathbb{F}_{47}$ with $\det(A) \not\equiv 0 \pmod{47}$.
4. **Sequential Chaining:** Applies CBC XOR block chaining with matrix transformation $B_i = A \times (x_i \oplus B_{i-1})$.
5. **Serialization:** Serializes each block into 24 Base-47 glyphs with a SHA-256 payload integrity tag.

---

## 7. Message Preprocessing

ECS validates that raw messages do not exceed $2^{32}$ bits (536,870,912 bytes).
The padded bitstream is formatted conceptually as:

```text
[32-bit Message Length L][L Message Bits][Fibonacci Padding Bits]
```

- If message length $L = 0$ (empty message), the first 32 bits are `0x00000000`, followed by 95 bits of Fibonacci padding to form a single 127-bit block.
- Total padded bit length is guaranteed to be a multiple of 127.

---

## 8. Fibonacci Padding

Padding bits are appended deterministically until the 127-bit block boundary is reached.
No random bits are used; padding is reproducible and verified upon decryption.

### Recurrence:
$$F_0 = 1, \quad F_1 = 1, \quad F_n = F_{n-1} + F_{n-2}$$

### Bit Generation Rule:
$$b_k = F_{k+1} \bmod 2 \quad (k \ge 0)$$

Generated sequence:
```text
1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, ...
```

Padding length:
$$P = (127 - ((32 + L) \bmod 127)) \bmod 127$$

Upon decryption, the exact original length $L$ is read from the first 32 bits, the message bits are extracted, and the padding sequence is verified. Any padding alteration raises `ECSInvalidCiphertext`.

---

## 9. SHA-256 Key Preprocessing

```text
key_hash = SHA256(key) = H0 || H1
```
where $H_0$ is the first 128 bits (bytes 0..15) and $H_1$ is the last 128 bits (bytes 16..31).

ECS implements an explicit cascading rule:
$$K_{128} = H_0 \oplus H_1$$
This incorporates all 256 bits of hash entropy into the 128-bit key material. An alternative prefix rule ($K_{128} = H_0$) is also available.

---

## 10. 127-Bit Message Block Specification

```python
MESSAGE_BLOCK_WIDTH = 127
MAX_BLOCK_VALUE = 2**127 - 1
```

Every plaintext, intermediate, and decrypted message block must strictly satisfy:
$$0 \le \text{block} \le 2^{127} - 1$$

Fixed-width binary representations preserve leading zeroes:
```python
format(block_value, "0127b")  # Exactly 127 characters
```

---

## 11. 127/128-Bit Domain Separation

```text
MESSAGE_BLOCK_WIDTH = 127
KEY_WIDTH           = 128
```

The 128th bit belongs strictly to the key domain, never to message blocks.
* A 127-bit message block is never promoted to 128 bits.
* No silent truncation via `& ((1 << 127) - 1)`.
* No silent wrapping via `% (2**127)`.
* Any message block operation producing $\ge 2^{127}$ raises `ECSBlockOverflowError`.

---

## 12. Base47 Conversion & Leading Zero Preservation

Since:
$$47^{22} < 2^{127} < 47^{23}$$
Every 127-bit integer can be uniquely represented by at most 23 Base-47 digits.
ECS pads each block to **24 digits** to form a clean $4 \times 6$ matrix representation:
$$24 \times \log_2(47) \approx 133.3 \text{ bits of capacity}$$

---

## 13. Matrix Transformation Layer

Linear transformation operates using $4 \times 4$ matrices over the finite field $\mathbb{F}_{47}$:
* **Key Matrix $A$:** $4 \times 4$ matrix in $\mathcal{M}_{4 \times 4}(\mathbb{F}_{47})$
* **Message Matrix $x$:** $4 \times 6$ matrix in $\mathcal{M}_{4 \times 6}(\mathbb{F}_{47})$
* **Cipher Matrix $B$:** $4 \times 6$ matrix in $\mathcal{M}_{4 \times 6}(\mathbb{F}_{47})$

Fundamental transformation:
$$B = A \times x \pmod{47}$$
Inverse transformation:
$$x = A^{-1} \times B \pmod{47}$$

---

## 14. Key Matrix Generation & Inversion

KeyMatrix $A$ is deterministically generated from $K_{128}$:
1. SHA-256 PRNG expands $K_{128}$ into 16 digits in $[0, 46]$.
2. Verifies $\det(A) \not\equiv 0 \pmod{47}$ via Gaussian elimination.
3. If singular, increments seed counter until non-singular.
4. Computes $A^{-1} \pmod{47}$ via Gauss-Jordan elimination.

---

## 15. Encryption Algorithm & Pseudocode

```text
Algorithm: ECS-Encrypt(Message, Key)
Input: Message bytes M, secret key K
Output: Serialized ciphertext string C

1. K_128 = SHA256(K)[0..15] XOR SHA256(K)[16..31]
2. A = GenerateKeyMatrix(K_128)
3. Bitstream = PadMessage(M)   // [32-bit length][message bits][Fibonacci padding]
4. Blocks = SplitInto127BitBlocks(Bitstream)  // x_1, x_2, ..., x_N
5. PrevChain = 0
6. For i = 1 to N:
     If i == 1:
       x_i' = x_1
     Else:
       x_i' = x_i XOR PrevChain
     Validate: 0 <= x_i' < 2^127
     X_i = MessageMatrix(x_i')
     B_i = (A * X_i) mod 47
     PrevChain = DeriveChain127(B_i)
7. Return Serialize(B_1, B_2, ..., B_N)
```

---

## 16. Decryption Algorithm & Pseudocode

```text
Algorithm: ECS-Decrypt(Ciphertext, Key)
Input: Serialized ciphertext C, secret key K
Output: Original message bytes M

1. K_128 = SHA256(K)[0..15] XOR SHA256(K)[16..31]
2. A = GenerateKeyMatrix(K_128)
3. B_1, B_2, ..., B_N = Deserialize(C)
4. PrevChain = 0
5. For i = 1 to N:
     X_i' = (A^(-1) * B_i) mod 47
     x_i' = X_i'.to_int()
     If i == 1:
       x_i = x_1'
     Else:
       x_i = x_i' XOR PrevChain
     Validate: 0 <= x_i < 2^127
     PrevChain = DeriveChain127(B_i)
6. Return UnpadMessage(x_1, x_2, ..., x_N)
```

---

## 17. Explicit Overflow Behavior

Arithmetic checks are centralized:
* `normalize_127(v)`: Raises `ECSBlockOverflowError` if $v \ge 2^{127}$, `ECSUnderflowError` if $v < 0$.
* `normalize_128(v)`: Raises `ECSOverflowError` if $v \ge 2^{128}$, `ECSUnderflowError` if $v < 0$.
* `normalize_base47(d)`: Validates $0 \le d < 47$.
* `checked_add`, `checked_sub`, `checked_mul`: Bounds-checked arithmetic.

---

## 18. Ciphertext Wire Format

```text
ECS<version>:<block_count>:<base47_payload>:<checksum>
```

Example:
```text
ECS1:2:762FCgIbCdqrfj?e2?F80000Dsa12GjFnzj4oklE2p$C!63g:aljd5vixr
```

* `ECS`: Magic prefix.
* `version`: Format revision (`1`).
* `block_count`: Integer count of 127-bit blocks.
* `base47_payload`: Concatenated 24-character Base-47 block strings.
* `checksum`: 8-character Base-47 SHA-256 integrity tag over payload.

---

## 19. Mathematical Notation

| Symbol | Definition |
| :--- | :--- |
| $\Sigma$ | 47-character alphabet (`0..z`, `1..9`, `! $ ?`, `B..I`) |
| $\mathcal{D}$ | Digit set $\{0, 1, 2, \dots, 46\}$ |
| $\mathbb{F}_{47}$ | Finite Galois field of prime characteristic 47 |
| $\oplus_{47}$ | Carryless addition: $(a \oplus_{47} b)_i = (a_i + b_i) \bmod 47$ |
| $\otimes_{47}$ | Carryless multiplication over $\mathbb{F}_{47}[x]$ |
| $\star_{47}$ | Quasigroup isotopic fold: $(2a_i + 3b_i + 1) \bmod 47$ |
| $K_{128}$ | 128-bit key material derived from SHA-256 |
| $A$ | Invertible $4 \times 4$ Key Matrix in $\mathcal{M}_{4 \times 4}(\mathbb{F}_{47})$ |
| $A^{-1}$ | Multiplicative inverse matrix in $\mathcal{M}_{4 \times 4}(\mathbb{F}_{47})$ |

---

## 20. Security Limitations & Non-Claims

> [!CAUTION]
> 1. **Not Standardized:** ECS has not undergone external cryptanalysis.
> 2. **Educational Model:** Linear transformations over small fields are susceptible to algebraic attacks without sufficient rounds and non-linear S-box layers.
> 3. **Non-Production:** Do not use ECS to protect sensitive passwords, financial transactions, or private communications.

---

## 21. Complete Code Examples & CLI

```python
from ecs import ECS, KeyMatrix, pad_message, unpad_message

# Low-level primitives
blocks = pad_message(b"Hello world")
print("Blocks (127-bit integers):", blocks)
recovered = unpad_message(blocks)
assert recovered == b"Hello world"

# Cipher instance
cipher = ECS("super_secret_key")
ct = cipher.encrypt_text("Research text message")
pt = cipher.decrypt_text(ct)
assert pt == "Research text message"
```

CLI Usage:
```bash
# File encryption
ecs encrypt -k "pass" -i document.pdf -o document.pdf.ecs

# File decryption
ecs decrypt -k "pass" -i document.pdf.ecs -o document_recovered.pdf
```

---

## 22. Automated Testing & Test Vectors

Run automated pytest tests (204 tests passing):
```bash
pytest -v
```

Test suite breakdown:
* `eb47ns/tests/`: 128 mathematical tests for arithmetic, number theory, polynomial rings, matrices, and CSPRNG.
* `tests/test_base47.py`: Alphabet bijections, valid/invalid symbols, and conversions.
* `tests/test_padding.py`: 32-bit header, Fibonacci sequence, and unpadding verification.
* `tests/test_overflow.py`: Strict $2^{127}$ and $2^{128}$ boundary tests.
* `tests/test_matrix.py`: $4 \times 4$ KeyMatrix invertibility and transformations.
* `tests/test_keys.py`: SHA-256 preprocessing and 128-bit key derivation.
* `tests/test_encryption.py` & `tests/test_decryption.py`: End-to-end round-trips and corruption rejection.
* `tests/test_edge_cases.py`: Boundary transitions and type checks.
* `tests/test_avalanche.py`: Hamming distance and avalanche measurement.

---

## 23. Development Instructions

```bash
# Clone repository
git clone https://github.com/Ezradestaw/eb47.git
cd eb47

# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate

# Install in development mode with test tools
pip install -e .[dev]

# Run tests
pytest

# Build package
python -m build

# Check distribution artifacts
twine check dist/*
```

---

## 24. License

This project is licensed under the **MIT License**. See the [LICENSE](LICENSE) file for details.

---

## 25. PyPI & TestPyPI Publication Instructions

### Build Artifacts
```bash
python -m build
twine check dist/*
```

### TestPyPI (Staging Verification)
```bash
python -m twine upload --repository testpypi dist/*
```

### Production PyPI
```bash
python -m twine upload dist/*
```
*(Use environment variables `TWINE_USERNAME=__token__` and `TWINE_PASSWORD=<token>` or repository secrets. Never hard-code tokens into source files).*
