TrinityCore
Loading...
Searching...
No Matches
TOTP.cpp
Go to the documentation of this file.
1/*
2 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "TOTP.h"
19#include <cstring>
20#include <openssl/evp.h>
21#include <openssl/hmac.h>
22
24static constexpr uint32 TOTP_INTERVAL = 30;
25static constexpr uint32 HMAC_RESULT_SIZE = 20;
26/*static*/ uint32 Trinity::Crypto::TOTP::GenerateToken(Secret const& secret, time_t timestamp)
27{
28 timestamp /= TOTP_INTERVAL;
29 unsigned char challenge[8];
30 for (int i = 8; i--; timestamp >>= 8)
31 challenge[i] = timestamp;
32
33 unsigned char digest[HMAC_RESULT_SIZE];
34 uint32 digestSize = HMAC_RESULT_SIZE;
35 HMAC(EVP_sha1(), secret.data(), secret.size(), challenge, 8, digest, &digestSize);
36
37 uint32 offset = digest[19] & 0xF;
38 uint32 truncated = (digest[offset] << 24) | (digest[offset + 1] << 16) | (digest[offset + 2] << 8) | (digest[offset + 3]);
39 truncated &= 0x7FFFFFFF;
40 return (truncated % 1000000);
41}
42
43/*static*/ bool Trinity::Crypto::TOTP::ValidateToken(Secret const& secret, uint32 token)
44{
45 time_t now = time(nullptr);
46 return (
47 (token == GenerateToken(secret, now - TOTP_INTERVAL)) ||
48 (token == GenerateToken(secret, now)) ||
49 (token == GenerateToken(secret, now + TOTP_INTERVAL))
50 );
51}
uint32_t uint32
Definition Define.h:133
static constexpr uint32 TOTP_INTERVAL
Definition TOTP.cpp:24
static constexpr uint32 HMAC_RESULT_SIZE
Definition TOTP.cpp:25
std::vector< uint8 > Secret
Definition TOTP.h:30
static bool ValidateToken(Secret const &key, uint32 token)
Definition TOTP.cpp:43
static uint32 GenerateToken(Secret const &key, time_t timestamp)
Definition TOTP.cpp:26
static constexpr size_t RECOMMENDED_SECRET_LENGTH
Definition TOTP.h:29