Skip to content

Core\Totp::code

Returns the current one-time code for a secret. This is the six-digit code that an authenticator app on a phone shows for two-factor login.

The server and the phone both keep the same secret. Each of them computes the code from the secret and the current time, so they get the same six digits without talking to each other. A new code starts every 30 seconds.

The code is a string, because a code can start with a zero. The secret must be at least 16 bytes long, and a shorter secret throws a LogicError. Core\Random::bytes(20) makes a secret of the recommended length.

Most programs only need check, which tests the code a user typed. code is useful when your own program must log in, for example in an automated test.

The examples show a code for a new secret, a secret that is too short, and a test that logs in to an account with two-factor login.

Parameters

  • $secretsecret bytesThe shared secret, at least 16 bytes long. Core\Random::bytes(20) makes one of the recommended length.

Return value

Returns string. Six digits as a string, with leading zeros, such as 042311. It is a string so that the leading zeros stay.

Errors

  • LogicError$secret is shorter than 16 bytes, or the clock is outside the range of dates a code can have.

Examples

A code for a new secret

<?nvs
// Shows how to make a secret for a new account and read its current code.
// `Core\Random::bytes(20)` makes a secret of 20 random bytes.
secret bytes $secret = Core\Random::bytes(20);
string $code = Core\Totp::code($secret);
// The code changes every 30 seconds, but it always has six characters.
// This prints 6.
echo Core\Str::length($code), "\n";
Output
6

A secret that is too short

<?nvs
// Shows what happens when the secret is shorter than 16 bytes.
secret bytes $short = Core\Random::bytes(8);
// A secret of 8 bytes is too easy to guess, so `code` throws a `LogicError`.
try {
echo Core\Totp::code($short), "\n";
} catch (LogicError $e) {
echo "The secret is too short.\n";
}
// A secret of 20 bytes is long enough. This prints 6.
echo Core\Str::length(Core\Totp::code(Core\Random::bytes(20))), "\n";
Output
The secret is too short.
6

Log in from an automated test

<?nvs
// Shows how an automated test logs in to an account that has two-factor login.
// The test account has its own secret, like every real account.
secret bytes $secret = Core\Random::bytes(20);
// A person reads the code from a phone. The test computes the same code instead.
string $typed = Core\Totp::code($secret);
// The login code of the server checks it. This prints "Logged in".
?int $step = Core\Totp::check($typed, $secret);
if ($step == null) {
echo "Wrong code\n";
} else {
echo "Logged in\n";
}
Output
Logged in