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 <openssl/evp.h>
20
#include <openssl/hmac.h>
21
22
static
constexpr
uint32
TOTP_INTERVAL
= 30;
23
static
constexpr
uint32
HMAC_RESULT_SIZE
= 20;
24
/*static*/
uint32
Trinity::Crypto::TOTP::GenerateToken
(
TOTP::Secret
const
& secret, time_t timestamp)
25
{
26
timestamp /=
TOTP_INTERVAL
;
27
unsigned
char
challenge[8];
28
for
(
int
i = 8; i--; timestamp >>= 8)
29
challenge[i] = timestamp;
30
31
unsigned
char
digest[
HMAC_RESULT_SIZE
];
32
uint32
digestSize =
HMAC_RESULT_SIZE
;
33
HMAC(EVP_sha1(), secret.data(), secret.size(), challenge, 8, digest, &digestSize);
34
35
uint32
offset = digest[19] & 0xF;
36
uint32
truncated = (digest[offset] << 24) | (digest[offset + 1] << 16) | (digest[offset + 2] << 8) | (digest[offset + 3]);
37
truncated &= 0x7FFFFFFF;
38
return
(truncated % 1000000);
39
}
40
41
/*static*/
bool
Trinity::Crypto::TOTP::ValidateToken
(
TOTP::Secret
const
& secret,
uint32
token)
42
{
43
time_t now = time(
nullptr
);
44
return
(
45
(token == GenerateToken(secret, now -
TOTP_INTERVAL
)) ||
46
(token == GenerateToken(secret, now)) ||
47
(token == GenerateToken(secret, now +
TOTP_INTERVAL
))
48
);
49
}
uint32
uint32_t uint32
Definition
Define.h:154
TOTP_INTERVAL
static constexpr uint32 TOTP_INTERVAL
Definition
TOTP.cpp:22
HMAC_RESULT_SIZE
static constexpr uint32 HMAC_RESULT_SIZE
Definition
TOTP.cpp:23
TOTP.h
Trinity::Crypto::TOTP::Secret
std::vector< uint8 > Secret
Definition
TOTP.h:30
Trinity::Crypto::TOTP::ValidateToken
static bool ValidateToken(Secret const &key, uint32 token)
Definition
TOTP.cpp:41
Trinity::Crypto::TOTP::GenerateToken
static uint32 GenerateToken(Secret const &key, time_t timestamp)
Definition
TOTP.cpp:24
common
Cryptography
TOTP.cpp
Generated on Sun May 10 2026 02:08:51 for TrinityCore by
1.9.8