Skip to content

csokosgeza/totp-qr-generator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TOTP QR Code Generator

A comprehensive RFC 6238 compliant Time-based One-Time Password (TOTP) implementation with QR code generation capabilities, built with TypeScript.

Features

  • RFC 6238 Compliant: Full implementation of the TOTP algorithm as specified in RFC 6238
  • Multiple Hash Algorithms: Support for SHA-1, SHA-256, and SHA-512
  • Flexible Digit Length: Support for 6, 7, and 8 digit OTPs
  • Secure Secret Generation: Cryptographically secure random secret key generation
  • Base32 Encoding: Full Base32 encoding/decoding support
  • Clock Drift Tolerance: Built-in support for time synchronization issues
  • QR Code Generation: Generate QR codes compatible with popular authenticator apps
  • Web Interface: User-friendly web interface for easy configuration and testing
  • TypeScript Support: Full TypeScript type safety
  • Comprehensive Testing: Extensive test suite with RFC 6238 test vectors

Table of Contents

  1. Installation
  2. Quick Start
  3. Usage
  4. API Reference
  5. Web Interface
  6. Testing
  7. Integration with Authenticator Apps
  8. Security Considerations
  9. Development
  10. Troubleshooting

Installation

Prerequisites

  • Node.js 16.0 or higher
  • npm 7.0 or higher

Clone and Install

# Clone the repository
git clone https://github.com/your-username/totp-qr-generator.git
cd totp-qr-generator

# Install dependencies
npm install

# Build the project
npm run build

Quick Start

1. Start the Web Interface

# Start the development server
npm run dev

# Or start the production server
npm start

The web interface will be available at http://localhost:3000

2. Generate Your First TOTP QR Code

  1. Open http://localhost:3000 in your browser
  2. Enter your account name (e.g., user@example.com)
  3. Enter your service provider (e.g., MyService)
  4. Click "Generate QR Code"
  5. Scan the QR code with your authenticator app

3. Verify the Implementation

  1. Use the built-in validator to verify generated codes
  2. Compare codes with your authenticator app
  3. Test different configurations (algorithms, digits, periods)

Usage

Basic TOTP Generation

import { TOTP } from './src/core/totp';

// Generate a TOTP with default parameters
const result = TOTP.generate({
  secret: 'JBSWY3DPEHPK3PXP' // Base32 encoded secret
});

console.log(result.otp); // 6-digit OTP
console.log(result.time); // Unix time used
console.log(result.timeStep); // Time step (default: 30)

Custom Parameters

// Generate TOTP with custom parameters
const result = TOTP.generate({
  secret: 'JBSWY3DPEHPK3PXP',
  timeStep: 60,        // 60-second time steps
  algorithm: 'sha256',  // Use SHA-256
  digits: 8,           // 8-digit OTP
  startTime: 1000000000 // Custom start time
}, 1000000060); // Specific time

OTP Verification

// Verify an OTP
const isValid = TOTP.verify('123456', {
  secret: 'JBSWY3DPEHPK3PXP'
});

// Verify with clock drift tolerance
const verification = TOTP.verifyWithWindow('123456', {
  secret: 'JBSWY3DPEHPK3PXP'
}, 1); // Allow ±1 time step

if (verification.valid) {
  console.log('Valid OTP at time:', verification.time);
}

Secret Generation

import { TOTP, Base32 } from './src/index';

// Generate a secure random secret
const secret = TOTP.generateSecret(20); // 20 bytes = 160 bits
console.log(secret); // Base32 encoded secret

// Or generate directly with Base32
const base32Secret = Base32.generateSecret(20);

QR Code Generation

import { QRCodeGenerator } from './src/qr/qrcode';
import { OtpAuth } from './src/qr/otpauth';

// Generate otpauth URI
const uri = OtpAuth.generateTOTPUri({
  label: 'MyService:user@example.com',
  secret: 'JBSWY3DPEHPK3PXP',
  issuer: 'MyService',
  algorithm: 'sha1',
  digits: 6,
  period: 30
});

// Generate QR code
const qrCode = await QRCodeGenerator.generate({
  otpauth: {
    label: 'MyService:user@example.com',
    secret: 'JBSWY3DPEHPK3PXP',
    issuer: 'MyService',
    algorithm: 'sha1',
    digits: 6,
    period: 30
  },
  width: 256,
  margin: 2,
  color: {
    dark: '#000000',
    light: '#FFFFFF'
  }
});

console.log(qrCode.dataUri); // Base64 data URI

API Reference

TOTP Class

Static Methods

  • generate(config: TOTPConfig, time?: number): TOTPResult

    • Generate a TOTP code with specified configuration
  • verify(otp: string, config: TOTPConfig, time?: number): boolean

    • Verify a TOTP code against the configuration
  • verifyWithWindow(otp: string, config: TOTPConfig, window: number, time?: number): { valid: boolean; time?: number; counter?: bigint }

    • Verify a TOTP code with time window tolerance
  • getRemainingTime(config: TOTPConfig, time?: number): number

    • Get remaining time until next TOTP refresh
  • getCurrentCounter(config: TOTPConfig, time?: number): bigint

    • Get current counter value for the given time
  • getTimeStepInfo(config: TOTPConfig, time?: number): TimeStepInfo

    • Get detailed time step information
  • generateSequence(config: TOTPConfig, count: number, startTime?: number): TOTPResult[]

    • Generate a sequence of TOTP codes
  • generateSecret(length?: number): string

    • Generate a secure random secret key

HOTP Class

Static Methods

  • generate(config: HOTPConfig): HOTPResult

    • Generate an HMAC-based One-Time Password
  • verify(otp: string, config: HOTPConfig): boolean

    • Verify an HOTP code
  • verifyWithWindow(otp: string, config: HOTPConfig, window: number): { valid: boolean; counter?: bigint }

    • Verify an HOTP code with counter window
  • generateSequence(config: HOTPConfig, count: number): HOTPResult[]

    • Generate a sequence of HOTP codes

QRCodeGenerator Class

Static Methods

  • generate(options: QRCodeOptions): Promise<QRCodeResult>

    • Generate a QR code as data URI
  • generateRaw(options: QRCodeOptions): Promise<Uint8Array>

    • Generate raw QR code data
  • generateSVG(options: QRCodeOptions): Promise<string>

    • Generate QR code as SVG
  • generateTerminal(options: QRCodeOptions, small?: boolean): Promise<string>

    • Generate QR code for terminal display

OtpAuth Class

Static Methods

  • generateTOTPUri(config: OtpAuthConfig): string

    • Generate otpauth URI for TOTP
  • parseUri(uri: string): OtpAuthParsed

    • Parse an otpauth URI
  • validateUri(uri: string): boolean

    • Validate an otpauth URI format

Web Interface

The TOTP QR Code Generator includes a user-friendly web interface that provides:

Features

  • Interactive Form: Easy configuration of TOTP parameters
  • Real-time Validation: Instant feedback on form inputs
  • QR Code Generation: Visual QR code generation with download options
  • TOTP Validator: Built-in validator to test generated codes
  • Code Timer: Visual countdown showing time until next refresh
  • Export Options: Download QR codes as PNG, SVG, or Base64

Usage

  1. Configure TOTP Parameters:

    • Account Name: Your email or username
    • Service Provider: Name of the service
    • Secret Key: Auto-generated or custom Base32 secret
    • Algorithm: SHA-1, SHA-256, or SHA-512
    • Digits: 6, 7, or 8 digits
    • Period: Time step in seconds (15-300)
  2. Generate QR Code:

    • Click "Generate QR Code" to create the QR code
    • Scan with your authenticator app
    • Use the validator to verify codes
  3. Export Options:

    • Download as PNG for easy sharing
    • Download as SVG for high-quality printing
    • Copy Base64 for web integration

Testing

Run All Tests

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

Test Categories

  1. Unit Tests: Test individual components and functions
  2. Integration Tests: Test component interactions and workflows
  3. Authenticator Compatibility: Test with popular authenticator apps
  4. Edge Cases: Test boundary conditions and error scenarios
  5. Performance Tests: Test under load and stress conditions

Test Documentation

Integration with Authenticator Apps

Supported Apps

The TOTP QR Code Generator has been tested with:

  • Google Authenticator (iOS/Android)
  • Microsoft Authenticator (iOS/Android)
  • Authy (iOS/Android/Desktop)
  • 1Password (iOS/Android/Desktop)
  • LastPass Authenticator (iOS/Android)
  • Authenticator Plus (iOS/Android)

Testing Steps

  1. Generate a QR code with your desired configuration
  2. Scan the QR code with your authenticator app
  3. Verify that the codes match between the app and web validator
  4. Test different configurations (algorithms, digits, periods)

For detailed testing instructions, see the Integration Guide.

Security Considerations

Secret Key Security

  • Minimum Length: Secret keys must be at least 160 bits (20 bytes)
  • Random Generation: Uses cryptographically secure random number generation
  • Base32 Encoding: Secrets are encoded using standard Base32 alphabet
  • Memory Protection: Sensitive data is zeroized after use

Implementation Security

  • Input Validation: All inputs are validated before processing
  • Error Handling: Errors are handled without exposing sensitive information
  • Time Security: Uses system time with fallback mechanisms
  • Algorithm Support: Implements only secure hash algorithms

Best Practices

  1. Use Strong Secrets: Always use the recommended minimum secret length
  2. Secure Storage: Store secrets securely in your application
  3. Regular Rotation: Rotate secrets periodically for enhanced security
  4. Backup Codes: Provide backup codes for account recovery
  5. Rate Limiting: Implement rate limiting for verification attempts

Development

Project Structure

qrkodgen/
├── src/
│   ├── core/           # Core TOTP implementation
│   │   ├── crypto.ts   # Cryptographic utilities
│   │   ├── base32.ts   # Base32 encoding/decoding
│   │   ├── hotp.ts     # HOTP implementation
│   │   └── totp.ts     # TOTP implementation
│   ├── qr/             # QR code generation
│   │   ├── qrcode.ts   # QR code generator
│   │   ├── otpauth.ts  # otpauth URI handling
│   │   └── export.ts   # Export functionality
│   └── ui/             # Web interface
│       ├── app.ts      # Main application
│       ├── components.ts # UI components
│       ├── validator.ts # TOTP validator
│       └── styles.css  # UI styles
├── tests/              # Test files
├── server.js           # Web server
├── package.json        # Dependencies and scripts
└── README.md          # This file

Development Scripts

# Start development server
npm run dev

# Build the project
npm run build

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

# Start production server
npm start

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

Troubleshooting

Common Issues

QR Code Not Scanning

Problem: Authenticator app cannot scan the generated QR code

Solutions:

  • Increase QR code size in the generator
  • Ensure good lighting when scanning
  • Check that the QR code contains valid data
  • Try a different authenticator app

Codes Don't Match

Problem: Codes in the authenticator app don't match the web validator

Solutions:

  • Check device time synchronization
  • Verify the secret key is identical
  • Confirm algorithm parameters match
  • Try rescanning the QR code

Verification Fails

Problem: Web validator rejects valid codes from the authenticator app

Solutions:

  • Increase the time window for verification
  • Check server time synchronization
  • Verify time step calculations
  • Test with a different time window

Performance Issues

Problem: Slow QR code generation or TOTP calculation

Solutions:

  • Check system resources
  • Reduce concurrent requests
  • Optimize QR code size
  • Use a more powerful server

Debug Mode

Enable debug mode to get detailed logging:

# Set debug environment variable
export DEBUG=totp:*

# Start the server
npm start

Getting Help

  1. Check the Integration Guide for testing issues
  2. Review the Test Scenarios for edge cases
  3. Search existing issues in the repository
  4. Create a new issue with detailed information

License

This implementation is provided for educational and development purposes. Please ensure compliance with relevant cryptographic regulations in your jurisdiction.

References

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors