SMS8

Build a real SMS OTP flow with your own Android phone

The end-to-end production pattern. Code generation, hashing, expiry, attempt caps, abuse limits, fallback channels.

Part of the guide Unlimited SMS OTP Sender: Verification API

On this page
  1. Key takeaways
  2. What does a good OTP flow look like end to end?
  3. How long should the OTP code be?
  4. How do I generate the code safely?
  5. Why must I hash the OTP before storing it?
  6. What is constant-time compare and why does it matter?
  7. What attempt and rate limits should I set?
  8. What does the full schema look like in MySQL?
  9. Full flow with the SMS8 OTP API
  10. How should I copy-write the SMS itself?
  11. Why use your own Android phone instead of Twilio Verify?
  12. What about fallback channels?
  13. Common bugs I have personally fixed
  14. What does Apple's iOS Messages autofill expect?
  15. Why choose SMS8 for OTP

Key takeaways

  • Six-digit codes, 10-minute expiry, max 5 attempts, max 5 sends per phone per 24h. That is a sane production default.
  • Store the hash of the OTP, not the OTP itself. Use SHA-256 with a server-side pepper.
  • Verify with hash_equals (PHP) or crypto.timingSafeEqual (Node). Never with ==.
  • Sending from your own SIM avoids Twilio Verify's $0.05 per successful verification plus SMS fees (as listed on their site in November 2026) and gives you a local sender number recipients trust.
  • Always have a fallback channel. SMS will fail for some user, some day.

The first OTP system I shipped had two bugs that would make a security engineer cry. The code was stored in plaintext. The compare was ==. We caught both during a routine pentest. After that I started writing the code samples below as a checklist, and I have used variants of them in every flow since. This post is the playbook I wish I had on day one. The SMS8 OTP API ships these protections by default and sends every code from your own number.

Most first OTP flows share the same handful of bugs, and the samples below avoid them. If you would rather not build the code storage yourself, the SMS8 OTP verification API generates and checks codes in two calls and sends them from your own number. For the wider context on Android gateways, start with the complete developer guide. For the verification checklist that complements this build guide, see phone number verification best practices.

What does a good OTP flow look like end to end?

Three endpoints, three states, two timers:

  1. POST /otp-send.php. Generate a 6-digit code, store its hash, send the SMS, return a token to the client.
  2. POST /otp-verify.php. Receive (phone, code), constant-time compare against the stored hash, mark consumed.
  3. GET /otp-status.php (optional). Tell the front-end how many attempts remain and when the user can request another code.

SMS8 ships endpoints 1 and 2 ready to go: POST https://app.sms8.io/ajax/otp-send.php and POST https://app.sms8.io/ajax/otp-verify.php. See the OTP API reference. AI agents can use the send_otp and verify_otp MCP tools instead. You can also build them yourself on top of the plain POST /api/v1/messages send call if you want full control.

How long should the OTP code be?

This is the question I get asked most often. The answer is six digits. Here is the math.

LengthPossible codesBrute-force success at 5 attemptsVerdict
4 digits10,0001 in 2,000 (~0.05%)Risky for high-value flows
5 digits100,0001 in 20,000 (~0.005%)Acceptable, unusual
6 digits1,000,0001 in 200,000 (~0.0005%)Recommended
7 digits10,000,0001 in 2,000,000Diminishing returns
8 digits100,000,0001 in 20,000,000Overkill, UX hit

Banks sometimes use 7 or 8 digits because their threat models include nation-state attackers and account values measured in five figures. For an e-commerce sign-up or a SaaS login, six digits is the right balance.

How do I generate the code safely?

Use a cryptographically-secure RNG. Not rand(), not mt_rand(), not Math.random(). Those are predictable enough that with a few observed codes an attacker can reconstruct the seed and predict future codes. NIST SP 800-22 covers this in painful detail.

// PHP 8+
$code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);

// Node 18+
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');

// Python 3.6+
import secrets
code = f"{secrets.randbelow(1_000_000):06d}"

// Go
import "crypto/rand"
import "math/big"
n, _ := rand.Int(rand.Reader, big.NewInt(1000000))
code := fmt.Sprintf("%06d", n.Int64())

Why must I hash the OTP before storing it?

If your database is dumped and the OTPs are plaintext, every active code is compromised. Hashing means even a leak buys the attacker nothing because the codes expire in minutes and are single-use. Plus you remove an entire class of audit findings.

// PHP
$pepper = getenv('OTP_PEPPER'); // never commit this
$hash = hash('sha256', $code . $pepper);
// Save $hash to DB, never $code

// Node
const pepper = process.env.OTP_PEPPER;
const hash = crypto.createHash('sha256').update(code + pepper).digest('hex');

// Python
import hashlib, os
pepper = os.environ['OTP_PEPPER']
hash_value = hashlib.sha256((code + pepper).encode()).hexdigest()

SHA-256 with a server-side pepper is fine here. You do not need bcrypt for a 10-minute-lifetime secret. The pepper protects against a DB-only leak (the attacker still needs to also exfiltrate your env vars, which is a much higher bar).

What is constant-time compare and why does it matter?

A naive string comparison returns false the moment two characters differ. Across thousands of HTTP requests an attacker can detect a few microseconds of timing difference per matched character. Use the framework-provided constant-time function instead.

// PHP - the right way
if (hash_equals($storedHash, hash('sha256', $submittedCode . $pepper))) {
    // valid
}

// Node
crypto.timingSafeEqual(
  Buffer.from(storedHash, 'hex'),
  Buffer.from(crypto.createHash('sha256').update(submittedCode + pepper).digest('hex'), 'hex')
);

// Python
import hmac
if hmac.compare_digest(stored_hash, hashlib.sha256((submitted + pepper).encode()).hexdigest()):
    pass  # valid

OWASP has a clear writeup on timing attacks at owasp.org and the HMAC construction itself is specified in RFC 2104.

What attempt and rate limits should I set?

  • Max 5 verify attempts per code. After that, invalidate the code and force a resend.
  • Max 5 OTP sends per phone per 24 hours. Stops the phone-bombing abuse pattern where someone uses your endpoint to spam a victim.
  • Cooldown of 60 seconds between sends. Lets legit users resend without DDoSing the carrier.
  • Per-IP rate limit of 20 sends per hour. Catches scripted abuse before it touches the SIM.
  • Per-user-account rate limit if your flow is for an authenticated action. Lower than per-phone.

What does the full schema look like in MySQL?

CREATE TABLE otps (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  phone         VARCHAR(20) NOT NULL,
  hash          CHAR(64) NOT NULL,           -- sha256 hex
  expires_at    INT UNSIGNED NOT NULL,        -- unix timestamp
  attempts      TINYINT UNSIGNED NOT NULL DEFAULT 0,
  consumed      TINYINT(1) NOT NULL DEFAULT 0,
  created_at    INT UNSIGNED NOT NULL,
  ip            VARCHAR(45),
  user_agent    VARCHAR(255),
  KEY idx_phone_active (phone, consumed, expires_at)
);

CREATE TABLE otp_send_log (
  phone         VARCHAR(20) NOT NULL,
  sent_at       INT UNSIGNED NOT NULL,
  ip            VARCHAR(45),
  KEY idx_phone (phone, sent_at),
  KEY idx_ip (ip, sent_at)
);

Full flow with the SMS8 OTP API

# 1. Send
curl -X POST https://app.sms8.io/ajax/otp-send.php \
  -d "api_key=YOUR_KEY" \
  -d "phone=+15551234567"
# { "success": true, "otp_id": 123, "expires_at": "...", "expires_in": 300 }

# 2. Verify
curl -X POST https://app.sms8.io/ajax/otp-verify.php \
  -d "api_key=YOUR_KEY" \
  -d "phone=+15551234567" \
  -d "code=482917"
# { "success": true, "verified": true, "otp_id": 123 }
# or { "success": true, "verified": false, "reason": "code_mismatch", "attempts_left": 3 }

The endpoint enforces the abuse caps (5 codes per phone per 24 hours, a 60-second resend cooldown by default, 5 attempts per code), the constant-time compare, and the expiry server-side. You do not have to reimplement any of that. If you prefer building your own, the PHP snippet below is what we run internally.

// /otp-send.php (your own server)
$phone = normalisePhone($_POST['phone']);
$ip = $_SERVER['REMOTE_ADDR'];
if (!$phone) return error('invalid_phone');
if (countRecentSends($phone, 86400) >= 5) return error('rate_limited_phone');
if (countRecentSendsByIp($ip, 3600) >= 20) return error('rate_limited_ip');

$code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
$hash = hash('sha256', $code . PEPPER);
$db->insert('otps', [
  'phone' => $phone,
  'hash' => $hash,
  'expires_at' => time() + 600,
  'created_at' => time(),
  'ip' => $ip,
]);
$db->insert('otp_send_log', ['phone' => $phone, 'sent_at' => time(), 'ip' => $ip]);
sms8Send($phone, "Your code is $code. Expires in 10 min.");
return ok(['expires_in' => 600]);

How should I copy-write the SMS itself?

This is the part most teams underthink. Here is what works:

  • Put the code first or last, not in the middle. Autofill on iOS (Messages -> one-time-code parsing) and Android parses better that way.
  • Include your brand name once. "Acme: your code is 482917" is fine.
  • End with "expires in 10 minutes." It heads off "is this code still valid" support tickets.
  • No links. Carriers downgrade links in OTPs and they invite phishing imitators that mimic your wording.
  • If the OTP is for a sensitive action, include the action: "Code to change your email: 482917". Stops attackers from tricking the user into reading the code aloud for a different purpose.

Why use your own Android phone instead of Twilio Verify?

It comes down to cost. At 20,000 verifications a month, Twilio Verify costs $1,000 in verification fees alone at the $0.05 per successful verification listed on their pricing page in November 2026, plus $0.0083 per US SMS. The same volume from a single Android phone with an unlimited SIM costs the USD 29 SMS8 plan plus whatever the SIM already costs you. Our Twilio alternatives comparison covers the rest of the Twilio bill.

SMS8 API page with an API key and a sample request
The SMS8 API page: your key, the send endpoint and delivery webhooks in one place.

What about fallback channels?

SMS will fail. The user will be on a flight, in a tunnel, on a number that was just ported and is briefly unreachable, or holding a phone with no signal. Every production OTP flow needs at least one fallback. The cheapest sane ladder is:

  1. SMS OTP (primary, lowest friction).
  2. Email OTP after SMS fails or after a 60-second timeout. Tell the user explicitly: "We sent you an email instead."
  3. TOTP authenticator for users who opted in (e.g. Google Authenticator). Lower friction once enrolled.
  4. Backup codes printed at enrolment, 10 single-use codes the user stores in a password manager.
  5. Manual support recovery as the final stop, with a clearly documented process and a 24-hour cool-down.

Common bugs I have personally fixed

BugSymptomFix
Whitespace in user inputVerify always failstrim() before compare
Unicode digitsRandom verify failures from Arabic / Persian keyboardsNormalise to ASCII digits (U+0660 to U+0669 maps to 0-9)
Code stored in plaintextAudit finding, leak riskHash with SHA-256 and a pepper
Same code accepted twiceReplay attackSet consumed = 1 on first valid verify
OTP sent to logged user's old numberAccount takeover riskRe-verify the phone number after any phone change; notify the old number
Verify works in dev but not prodServer clock driftNTP sync; never use time() without checking against a known-good source
"My code is 000000" attacksRNG was Math.random()Use cryptographic RNG

What does Apple's iOS Messages autofill expect?

iOS will autofill any 4 to 8 digit number in a recent SMS into a one-time-code text field, but the experience is much smoother if you include the @domain.com #code hint. Format:

Your Acme code is 482917. Do not share.

@acme.com #482917

The second paragraph (separated by a blank line) is the magic. iOS reads it, matches your domain, and offers the autofill keyboard chip even before the user opens the app. Google's WebOTP API on Android Chrome behaves similarly. Read the spec at web.dev/articles/web-otp.

Why choose SMS8 for OTP

SMS8 ships these patterns in its OTP API, so you get them without writing them.

  • OTP built in. Send and verify a code in two calls, from your own number, with no fee per code.
  • Your own number. Texts leave from the SIM in your own Android phone, so customers see a number they know and can reply to.
  • A flat price with unlimited messages. USD 29 a month for one phone or Mac, USD 89 for five and USD 229 for twenty, with unlimited SMS and MMS and no per-message fee. Yearly billing is half the price.
  • No A2P 10DLC filing. Texts go person-to-person from your SIM, so there is no brand, campaign or monthly campaign fee to manage.
  • A developer-friendly API. POST https://app.sms8.io/api/v1/messages with an X-Api-Key header, signed webhooks retried for up to 30 days, and npm install sms8-sdk for the SDK and the sms8 CLI.

Start the 3-day trial with 30 messages and no card, or compare plans on the SMS8 pricing page.

Common questions

Still unsure? We answer fast.

Six digits. The math is in the table above.

Five to ten minutes. SMS8 defaults to five (300 seconds) and accepts 60 to 900.

It defeats timing side-channel attacks that learn the code one character at a time.

Yes for moderate volumes. Multi-device routing handles higher volume.

Per-phone cap, per-IP cap, captcha on unauthenticated send-OTP requests.

SMS for consumer apps. TOTP plus SMS fallback for high-value targets.

Ship OTPs from your own phone

Six-digit codes, hashed and rate-limited, sent from your own SIM with no per-message fee.