Skip to content

RKG765/otp_generator_recursive_function

Repository files navigation

🔐 Recurrence-Based Time OTP Authentication System

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.

📋 Table of Contents


✨ Features

Core Features

  • 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

Advanced Features

  • 🔄 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

🏗️ System Architecture

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    │ │
              │   └──────────────────┘ │
              └────────────────────────┘

Component Details

  1. 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)
  2. OTP Generator (streamlit_generator.py)

    • Generates time-based OTPs
    • Displays mathematical calculations
    • Custom validity slider (15-120s)
    • Manual regeneration button
    • Auto-syncs with backend
  3. OTP Verifier (streamlit_verifier.py)

    • Verifies OTPs via API
    • Shows live mathematical formula
    • Displays all variable values
    • Real-time time-slice tracking

🧮 Mathematical Foundation

Recurrence Relation

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

OTP Generation Process

  1. Calculate time slice: t = current_timestamp // validity_duration
  2. Square the seed: X_n² = seed²
  3. Apply recurrence relation: X_(n+1) = (a × X_n² + b × t + c) mod m
  4. Extract 6-digit OTP: OTP = X_(n+1) mod 1,000,000

Example Calculation

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**

🚀 Installation

Prerequisites

  • Python 3.10+ installed on your system
  • pip package manager
  • Windows OS (for .bat scripts; adapt for Linux/Mac)

Quick Installation

  1. Clone or download the project to your desired directory

  2. Run the setup script:

    setup.bat

    This will:

    • Create a virtual environment
    • Install all required dependencies
    • Display instructions for running the system

Manual Installation

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.txt

💻 Usage

Method 1: Automated Launch (Recommended)

Simply run the all-in-one launcher:

run_all.bat

This will automatically start all three components in separate terminal windows.

Method 2: Manual Launch

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 8000

Terminal 2 - OTP Generator:

venv\Scripts\activate
streamlit run streamlit_generator.py --server.port 8501 --server.enableCORS false --browser.gatherUsageStats false

Terminal 3 - OTP Verifier:

venv\Scripts\activate
streamlit run streamlit_verifier.py --server.port 8502 --server.enableCORS false --browser.gatherUsageStats false

Accessing the Applications

Once running, access the following URLs in your browser:


🌐 Network Access

Enabling Network Access

The system is pre-configured for network access. To use it across your network:

  1. Start the backend server (it listens on 0.0.0.0 by default)

  2. Find your local IP address:

    • Windows: Run ipconfig in Command Prompt
    • Linux/Mac: Run ifconfig or ip addr
    • Look for your IPv4 address (e.g., 192.168.1.100)
  3. Update config.py on client devices:

    api_url = "http://192.168.1.100:8000"  # Replace with your server IP
  4. Access the applications from other devices:

Firewall Configuration

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

⚙️ Configuration

Configuration File: config.py

# 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

Customization Options

  1. Change Default Validity: Modify time_slice_duration (default: 45s)
  2. Adjust Validity Range: Change min_validity and max_validity
  3. Change API Key: Update api_key for enhanced security
  4. Network Access: Update api_url with server IP address
  5. Mathematical Constants: Modify a, b, c, m for different sequences

📚 API Documentation

Base URL

http://localhost:8000

Endpoints

1. Get Root Information

GET /

Returns API information and available endpoints.

2. Update OTP

POST /otp/update
Headers: X-API-KEY: SECRET_KEY
Content-Type: application/json

Body:
{
  "otp": "123456",
  "timestamp": 1699999999,
  "time_slice": 37777,
  "validity_duration": 45
}

3. Verify OTP

POST /otp/verify
Headers: X-API-KEY: SECRET_KEY
Content-Type: application/json

Body:
{
  "otp": "123456"
}

Response:
{
  "valid": true,
  "message": "OTP is valid"
}

4. Get Current OTP

GET /otp/current

Response:
{
  "otp": "123456",
  "timestamp": 1699999999,
  "time_slice": 37777,
  "expired": false
}

5. Health Check

GET /health

Response:
{
  "status": "healthy",
  "timestamp": 1699999999
}

Interactive API Documentation

Visit http://localhost:8000/docs for interactive Swagger UI documentation where you can test all endpoints directly in your browser.


🔒 Security Considerations

Current Security Measures

  1. API Key Authentication: All sensitive endpoints require valid API key
  2. Time-Based Expiration: OTPs expire after validity window
  3. Large Prime Modulus: Uses 1,000,000,007 for cryptographic strength
  4. HTTPS Ready: Can be deployed with SSL/TLS certificates

Production Recommendations

For production deployment, consider:

  1. Use HTTPS: Deploy with SSL/TLS certificates
  2. Strong API Keys: Use long, random API keys
  3. Rate Limiting: Implement rate limiting on API endpoints
  4. Database Storage: Replace in-memory storage with persistent database
  5. Logging: Add comprehensive logging and monitoring
  6. Environment Variables: Store sensitive config in environment variables
  7. CORS Configuration: Restrict CORS to specific origins
  8. Firewall Rules: Limit network access to trusted IPs

Known Limitations

  • 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)

🔧 Troubleshooting

Common Issues

1. "Cannot connect to server"

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_url in config.py is correct
  • Try accessing http://localhost:8000/health in browser

2. "Port already in use"

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 :8000 to find conflicting process

3. "OTP verification fails"

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

4. "Virtual environment not found"

Problem: run_all.bat can't find venv.

Solutions:

  • Run setup.bat first to create virtual environment
  • Verify venv folder exists in project directory

5. Network access issues

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.py with correct server IP address
  • Ensure devices are on same network

📊 Project Structure

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)

🎯 Features Checklist

  • ✅ 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

📝 License

This project is provided as-is for educational and demonstration purposes.


🤝 Contributing

This is a demonstration project. Feel free to fork and modify according to your needs.


📞 Support

For issues, questions, or suggestions:

  1. Check the Troubleshooting section
  2. Review the API documentation at http://localhost:8000/docs
  3. Verify all configuration settings in config.py

🎓 Educational Purpose

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

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •