A comprehensive RFC 6238 compliant Time-based One-Time Password (TOTP) implementation with QR code generation capabilities, built with TypeScript.
- 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
- Installation
- Quick Start
- Usage
- API Reference
- Web Interface
- Testing
- Integration with Authenticator Apps
- Security Considerations
- Development
- Troubleshooting
- Node.js 16.0 or higher
- npm 7.0 or higher
# 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# Start the development server
npm run dev
# Or start the production server
npm startThe web interface will be available at http://localhost:3000
- Open
http://localhost:3000in your browser - Enter your account name (e.g.,
user@example.com) - Enter your service provider (e.g.,
MyService) - Click "Generate QR Code"
- Scan the QR code with your authenticator app
- Use the built-in validator to verify generated codes
- Compare codes with your authenticator app
- Test different configurations (algorithms, digits, periods)
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)// 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// 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);
}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);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-
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
-
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
-
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
-
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
The TOTP QR Code Generator includes a user-friendly web interface that provides:
- 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
-
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)
-
Generate QR Code:
- Click "Generate QR Code" to create the QR code
- Scan with your authenticator app
- Use the validator to verify codes
-
Export Options:
- Download as PNG for easy sharing
- Download as SVG for high-quality printing
- Copy Base64 for web integration
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch- Unit Tests: Test individual components and functions
- Integration Tests: Test component interactions and workflows
- Authenticator Compatibility: Test with popular authenticator apps
- Edge Cases: Test boundary conditions and error scenarios
- Performance Tests: Test under load and stress conditions
- Integration Guide: Detailed guide for testing with authenticator apps
- Test Scenarios: Comprehensive test scenarios and cases
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)
- Generate a QR code with your desired configuration
- Scan the QR code with your authenticator app
- Verify that the codes match between the app and web validator
- Test different configurations (algorithms, digits, periods)
For detailed testing instructions, see the Integration Guide.
- 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
- 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
- Use Strong Secrets: Always use the recommended minimum secret length
- Secure Storage: Store secrets securely in your application
- Regular Rotation: Rotate secrets periodically for enhanced security
- Backup Codes: Provide backup codes for account recovery
- Rate Limiting: Implement rate limiting for verification attempts
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
# 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- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
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
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
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
Problem: Slow QR code generation or TOTP calculation
Solutions:
- Check system resources
- Reduce concurrent requests
- Optimize QR code size
- Use a more powerful server
Enable debug mode to get detailed logging:
# Set debug environment variable
export DEBUG=totp:*
# Start the server
npm start- Check the Integration Guide for testing issues
- Review the Test Scenarios for edge cases
- Search existing issues in the repository
- Create a new issue with detailed information
This implementation is provided for educational and development purposes. Please ensure compliance with relevant cryptographic regulations in your jurisdiction.