Verification codes are generated using a cryptographically secure random number generator (CSPRNG), not a simple Math.random() function, because security depends on unpredictability. This article explains how those numbers are created, why they are secure, and what you should know when choosing or implementing one.
Why Randomness Matters for Verification Codes
A verification code (like a 6-digit SMS code or a 2FA token) is a secret that grants access. If an attacker can predict the code, they can bypass the security. For example, a code generated with a weak random source might follow a pattern or be seeded by the current time, making it guessable. Cryptographic randomness ensures that each code is independent and uniformly distributed, so no one can predict the next one without knowing the secret seed.
How Random Number Generators Work
Random number generators fall into two categories:
- True Random Number Generators (TRNGs) – These use physical phenomena like electronic noise or radioactive decay. They are truly unpredictable but often slow and hardware-dependent.
- Pseudo-Random Number Generators (PRNGs) – These use algorithms to produce sequences that appear random. They are fast and deterministic, but their security depends on the quality of the seed and the algorithm.
For security, we use cryptographically secure PRNGs (CSPRNGs) that are designed to withstand statistical attacks. Examples include ChaCha20, HMAC_DRBG, and Fortuna. They are seeded with high-entropy data from the operating system (e.g., /dev/urandom on Linux, CryptGenRandom on Windows).
How Verification Codes Are Generated
Most verification codes are generated using a standard algorithm like TOTP (Time-based One-Time Password) or HOTP (HMAC-based One-Time Password). Here’s a simplified breakdown:
- Generate a random secret key (e.g., 160-bit) using a CSPRNG.
- For TOTP, combine the secret with the current time step (usually 30 seconds) using HMAC-SHA1 or SHA-256.
- Truncate the hash to a 6-digit number (or 8, 10, etc.) using the dynamic truncation method defined in RFC 4226/6238.
- Send that number to the user via SMS, email, or authenticator app.
For simple SMS codes, some services just generate a random integer between 100000 and 999999 using a CSPRNG. The key is that the generation process must be unpredictable and each code should be valid only for a short period (e.g., 5–10 minutes) and used only once.
Choosing a Random Number Generator for Your App
If you are a developer implementing verification codes, never use Math.random() or rand() from standard libraries. Instead, use language-specific secure APIs:
- JavaScript:
crypto.getRandomValues()(browser) orcrypto.randomInt()(Node.js). - Python:
secrets.randbelow()orsecrets.token_hex(). - Java:
java.security.SecureRandom. - C#:
System.Security.Cryptography.RandomNumberGenerator.
For example, in Node.js you could generate a 6-digit code with:
const crypto = require('crypto');
const code = crypto.randomInt(0, 1000000).toString().padStart(6, '0');
This uses a cryptographically secure source. Always ensure the code is stored hashed (like a password) if you need to verify it later, and never log it.
Common Problems with Verification Codes
Even with secure generation, issues arise:
- Brute force: If the code is 6 digits, there are only 1 million possibilities. Attackers may try many codes quickly. Mitigate by limiting attempts (e.g., 5 tries) and adding rate limiting.
- Timing attacks: If your comparison is not constant-time, an attacker might measure how long verification takes to guess the code. Use constant-time comparison functions.
- Reuse: Codes should be single-use and expire after a short time (e.g., 5 minutes). Otherwise, a stolen code remains valid.
- Phishing: Users can be tricked into giving codes to fake websites. Educate users and consider using authenticator apps instead of SMS.
Comparing SMS Codes vs. Authenticator Apps
Both use random numbers, but they differ in security and convenience:
- SMS codes: Easy for users, but vulnerable to SIM swapping and interception. The code is sent over the phone network, which is not encrypted.
- Authenticator apps (TOTP): The code is generated locally on the device using a shared secret. No message is sent, so interception is harder. However, if the device is compromised, codes can be stolen.
- Hardware tokens: Generate codes offline, often with a button press. Most secure but less convenient.
For high-security accounts, authenticator apps or hardware tokens are recommended over SMS.
Costs and Implementation Considerations
Generating a random number itself is free, but sending SMS codes costs money (typically $0.05–$0.10 per message depending on provider and region). Email codes are cheaper but less secure. If you are building a system, consider the cost of SMS delivery and the risk of fraud. Using TOTP apps eliminates delivery costs but requires users to install an app. Also, you must comply with data protection regulations when storing user phone numbers.
Safety and Best Practices
To keep verification codes secure:
- Use at least 6 digits; 8 digits are better for high-value actions.
- Expire codes after 5–10 minutes.
- Limit attempts (e.g., 5–10) and lock the account after repeated failures.
- Never send the same code twice.
- Hash the code before storing (e.g., SHA-256 with a random salt).
- Use HTTPS for all communication.
- Do not include the code in URLs or logs.
Frequently Asked Questions
Is it safe to use a random number from a website generator?
No. Online random number generators are not secure because you don’t know their source or whether they are truly random. For verification codes, always use a trusted library or service that uses CSPRNG.
Why are verification codes usually 6 digits?
Six digits offer a balance between security and usability. With 1 million combinations and rate limiting, it’s hard to brute-force. Longer codes are harder to remember and type, especially on mobile.
Can a verification code be predicted if I know the time?
For TOTP codes, knowing the time helps narrow the window, but without the secret key, you cannot predict the code. The secret is randomly generated and kept on the server and device.
What should I do if I receive a verification code I didn’t request?
Do not enter it anywhere. It may indicate someone is trying to access your account. Change your password and enable additional security like two-factor authentication.
How do I generate a random number in Excel for a code?
Excel’s RAND() is not cryptographically secure. For a random 6-digit number, you could use =RANDBETWEEN(100000,999999), but it’s not suitable for security. Use a dedicated secure generator or a programming language.
Conclusion
Random number generation for verification codes is a critical security measure. Always use a cryptographically secure source, follow best practices for expiration and rate limiting, and educate users about phishing. The next time you enter a 6-digit code, rest assured that behind it is a carefully designed system ensuring unpredictability.
Related
- Oracle Generate Random Number: DBMS_RANDOM Explained
- Understanding QuickBooks Balance Sheet Basics
- IMTANH in Google Sheets: Hyperbolic Tangent of Complex Numbers
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Equity Bank Balance Sheet: Key FactsEquity Bank’s balance sheet shows total assets of approximately KSh 1.6 trillion as of December 2023, with customer…
- Excel Developer Tab: How to Open It on Windows and MacIn Excel for Microsoft 365 on Windows, select File > Options > Customize Ribbon, check Developer under Main…
- What Is a Data Entry Analyst? Role, Skills, PayA data entry analyst is a professional who combines the core duties of a data entry clerk with…
- Shortcut to Close All Tabs? Quick Keys & StepsThe fastest way to close all tabs in a browser is to press Ctrl+Shift+W on Windows or Cmd+Shift+W…
- Microsoft Excel Solver: How It Works and When to Use ItMicrosoft Excel Solver is an optimization add-in that finds values for selected cells to maximize or minimize a…
- Can You Remove a Page Break in Word? Here’s How to Do ItYes. In Word for Microsoft 365 on Windows, show formatting marks with Ctrl+Shift+8, select the Manual Page Break…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.