A transparent and secure One-Time Password (OTP) authentication system built using mathematical recurrence relations and time-based synchronization. This system provides complete mathematical transparency while maintaining security through cryptographic principles.
- Features
- System Architecture
- Mathematical Foundation
- Installation
- Usage
- Network Access
- Configuration
- API Documentation
- Security Considerations
- Troubleshooting
- ✅ Time-Based OTP Generation: Generates 6-digit OTPs using mathematical recurrence relations
- ✅ Custom Validity Window: Default 45 seconds with customizable range (15-120 seconds)
- ✅ Manual Regeneration: Force immediate OTP regeneration at any time
- ✅ Mathematical Transparency: Display all formula variables and calculations in real-time
- ✅ Live Time-Slice Index: Real-time display of current time slice and countdown
- ✅ Network Accessible: Share across entire network for multi-device access
- ✅ REST API Backend: FastAPI-powered server with OpenAPI documentation
- ✅ Dual UI: Separate generator and verifier applications
- 🔄 Auto-refresh with live countdown timers
- 📊 Real-time mathematical calculation display
- 🎮 Interactive validity slider (15-120 seconds)
- 🌐 CORS-enabled for cross-origin requests
- 📝 Complete API documentation with Swagger UI
- 🔒 API key authentication
- ⚡ Fast and responsive UI built with Streamlit
The system consists of three main components:
┌─────────────────────────────────────────────────────────┐
│ Client Applications │
│ ┌──────────────────────┐ ┌──────────────────────┐ │
│ │ OTP Generator │ │ OTP Verifier │ │
│ │ (Streamlit) │ │ (Streamlit) │ │
│ │ Port: 8501 │ │ Port: 8502 │ │
│ └──────────┬───────────┘ └──────────┬───────────┘ │
│ │ │ │
│ └───────────┬───────────────┘ │
└─────────────────────────┼───────────────────────────────┘
│
│ REST API
▼
┌────────────────────────┐
│ FastAPI Backend │
│ Port: 8000 │
│ ┌──────────────────┐ │
│ │ OTP Storage │ │
│ │ Verification │ │
│ └──────────────────┘ │
└────────────────────────┘
-
FastAPI Backend Server (
fastapi_server.py)- Handles OTP storage and verification
- Provides REST API endpoints
- Manages custom validity durations
- Network-accessible on all interfaces (0.0.0.0)
-
OTP Generator (
streamlit_generator.py)- Generates time-based OTPs
- Displays mathematical calculations
- Custom validity slider (15-120s)
- Manual regeneration button
- Auto-syncs with backend
-
OTP Verifier (
streamlit_verifier.py)- Verifies OTPs via API
- Shows live mathematical formula
- Displays all variable values
- Real-time time-slice tracking
The OTP generation uses the following recurrence relation:
X_(n+1) = (a × X_n² + b × t + c) mod m
Where:
- X_n: Current seed value
- X_(n+1): Next seed value (also used for OTP generation)
- a = 13: Multiplier for squared seed
- b = 7: Multiplier for time component
- c = 17: Additive constant
- m = 1,000,000,007: Large prime modulus for security
- t: Current time slice index
- Initial seed = 123,456,789
- Calculate time slice:
t = current_timestamp // validity_duration - Square the seed:
X_n² = seed² - Apply recurrence relation:
X_(n+1) = (a × X_n² + b × t + c) mod m - Extract 6-digit OTP:
OTP = X_(n+1) mod 1,000,000
Given:
- Seed (X_n) = 123,456,789
- Time slice (t) = 38,000
- Constants: a=13, b=7, c=17, m=1,000,000,007
Step 1: X_n² = 123,456,789² = 15,241,578,750,190,521
Step 2: Calculate terms
a × X_n² = 13 × 15,241,578,750,190,521 = 198,140,523,752,476,773
b × t = 7 × 38,000 = 266,000
c = 17
Step 3: Sum = 198,140,523,752,476,773 + 266,000 + 17 = 198,140,523,752,742,790
Step 4: X_(n+1) = 198,140,523,752,742,790 mod 1,000,000,007 = 742,784
Step 5: OTP = 742,784 mod 1,000,000 = 742784 → **742784**
- Python 3.10+ installed on your system
- pip package manager
- Windows OS (for .bat scripts; adapt for Linux/Mac)
-
Clone or download the project to your desired directory
-
Run the setup script:
setup.bat
This will:
- Create a virtual environment
- Install all required dependencies
- Display instructions for running the system
If you prefer manual installation:
# Create virtual environment
python -m venv venv
# Activate virtual environment
# Windows:
venv\Scripts\activate
# Linux/Mac:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txtSimply run the all-in-one launcher:
run_all.batThis will automatically start all three components in separate terminal windows.
Open three separate terminal windows and run each component:
Terminal 1 - Backend Server:
venv\Scripts\activate
python -m uvicorn fastapi_server:app --reload --host 0.0.0.0 --port 8000Terminal 2 - OTP Generator:
venv\Scripts\activate
streamlit run streamlit_generator.py --server.port 8501 --server.enableCORS false --browser.gatherUsageStats falseTerminal 3 - OTP Verifier:
venv\Scripts\activate
streamlit run streamlit_verifier.py --server.port 8502 --server.enableCORS false --browser.gatherUsageStats falseOnce running, access the following URLs in your browser:
- Backend API: http://localhost:8000
- API Documentation: http://localhost:8000/docs
- OTP Generator: http://localhost:8501
- OTP Verifier: http://localhost:8502
The system is pre-configured for network access. To use it across your network:
-
Start the backend server (it listens on 0.0.0.0 by default)
-
Find your local IP address:
- Windows: Run
ipconfigin Command Prompt - Linux/Mac: Run
ifconfigorip addr - Look for your IPv4 address (e.g., 192.168.1.100)
- Windows: Run
-
Update
config.pyon client devices:api_url = "http://192.168.1.100:8000" # Replace with your server IP
-
Access the applications from other devices:
- Backend: http://192.168.1.100:8000
- Generator: http://192.168.1.100:8501
- Verifier: http://192.168.1.100:8502
Ensure these ports are open in your firewall:
- 8000: FastAPI Backend
- 8501: OTP Generator
- 8502: OTP Verifier
Windows Firewall Example:
netsh advfirewall firewall add rule name="OTP Backend" dir=in action=allow protocol=TCP localport=8000
netsh advfirewall firewall add rule name="OTP Generator" dir=in action=allow protocol=TCP localport=8501
netsh advfirewall firewall add rule name="OTP Verifier" dir=in action=allow protocol=TCP localport=8502# Recurrence relation constants
a = 13 # Multiplier for squared seed
b = 7 # Multiplier for time component
c = 17 # Additive constant
m = 1000000007 # Large prime modulus
seed = 123456789 # Initial seed value
# API Configuration
api_url = "http://localhost:8000" # Backend server URL
api_key = "SECRET_KEY" # API authentication key
# Time Configuration
time_slice_duration = 45 # Default OTP validity (seconds)
min_validity = 15 # Minimum validity (seconds)
max_validity = 120 # Maximum validity (seconds)
# OTP Configuration
otp_digits = 6 # Number of digits in OTP
otp_modulus = 10 ** otp_digits # 1,000,000 for 6-digit OTP- Change Default Validity: Modify
time_slice_duration(default: 45s) - Adjust Validity Range: Change
min_validityandmax_validity - Change API Key: Update
api_keyfor enhanced security - Network Access: Update
api_urlwith server IP address - Mathematical Constants: Modify
a,b,c,mfor different sequences
http://localhost:8000
GET /Returns API information and available endpoints.
POST /otp/update
Headers: X-API-KEY: SECRET_KEY
Content-Type: application/json
Body:
{
"otp": "123456",
"timestamp": 1699999999,
"time_slice": 37777,
"validity_duration": 45
}POST /otp/verify
Headers: X-API-KEY: SECRET_KEY
Content-Type: application/json
Body:
{
"otp": "123456"
}
Response:
{
"valid": true,
"message": "OTP is valid"
}GET /otp/current
Response:
{
"otp": "123456",
"timestamp": 1699999999,
"time_slice": 37777,
"expired": false
}GET /health
Response:
{
"status": "healthy",
"timestamp": 1699999999
}Visit http://localhost:8000/docs for interactive Swagger UI documentation where you can test all endpoints directly in your browser.
- API Key Authentication: All sensitive endpoints require valid API key
- Time-Based Expiration: OTPs expire after validity window
- Large Prime Modulus: Uses 1,000,000,007 for cryptographic strength
- HTTPS Ready: Can be deployed with SSL/TLS certificates
For production deployment, consider:
- Use HTTPS: Deploy with SSL/TLS certificates
- Strong API Keys: Use long, random API keys
- Rate Limiting: Implement rate limiting on API endpoints
- Database Storage: Replace in-memory storage with persistent database
- Logging: Add comprehensive logging and monitoring
- Environment Variables: Store sensitive config in environment variables
- CORS Configuration: Restrict CORS to specific origins
- Firewall Rules: Limit network access to trusted IPs
- In-Memory Storage: Current implementation stores OTP in memory
- Single Server: No redundancy or load balancing
- Simple API Key: Uses static API key (should use tokens in production)
Problem: Generator/Verifier can't reach the backend.
Solutions:
- Ensure backend server is running
- Check that port 8000 is not blocked by firewall
- Verify
api_urlinconfig.pyis correct - Try accessing http://localhost:8000/health in browser
Problem: Another application is using the required port.
Solutions:
- Stop other applications using ports 8000, 8501, 8502
- Change ports in run commands
- Use
netstat -ano | findstr :8000to find conflicting process
Problem: Valid OTP is not accepted.
Solutions:
- Check system time synchronization
- Verify validity duration matches between generator and server
- Ensure OTP hasn't expired
- Check API key is correct
Problem: run_all.bat can't find venv.
Solutions:
- Run
setup.batfirst to create virtual environment - Verify venv folder exists in project directory
Problem: Can't access from other devices.
Solutions:
- Check firewall settings (ports 8000, 8501, 8502)
- Verify server is running with
--host 0.0.0.0 - Update
config.pywith correct server IP address - Ensure devices are on same network
DM/
│
├── config.py # Configuration file
├── fastapi_server.py # Backend REST API server
├── streamlit_generator.py # OTP Generator UI
├── streamlit_verifier.py # OTP Verifier UI
│
├── requirements.txt # Python dependencies
├── setup.bat # Installation script
├── run_all.bat # Unified launcher
├── README.md # This documentation
│
└── venv/ # Virtual environment (created by setup)
- ✅ Default OTP validity window = 45 seconds
- ✅ Custom validity slider (15-120 seconds)
- ✅ Manual OTP regeneration button
- ✅ Display mathematical recurrence formula
- ✅ Show all variable values in real-time
- ✅ Display current time-slice index live
- ✅ Network-shareable across entire network
- ✅ Comprehensive README.md
- ✅ Setup scripts for easy installation
- ✅ REST API with full documentation
This project is provided as-is for educational and demonstration purposes.
This is a demonstration project. Feel free to fork and modify according to your needs.
For issues, questions, or suggestions:
- Check the Troubleshooting section
- Review the API documentation at http://localhost:8000/docs
- Verify all configuration settings in
config.py
This system demonstrates:
- Mathematical recurrence relations in cryptography
- Time-based OTP generation
- REST API design with FastAPI
- Real-time web applications with Streamlit
- Network application architecture
- Mathematical transparency in security systems
Built with ❤️ using FastAPI, Streamlit, and Python