2018-01-14 17:17:34 +11:00
|
|
|
/*
|
2018-08-04 15:18:16 +10:00
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
2018-01-14 17:17:34 +11:00
|
|
|
*
|
|
|
|
* Copyright 2015-2018 Danny Robson <danny@nerdcruft.net>
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include "hotp.hpp"
|
|
|
|
|
|
|
|
#include <cruft/util/endian.hpp>
|
|
|
|
|
|
|
|
#include <cstring>
|
|
|
|
|
|
|
|
using cruft::crypto::hash::HOTP;
|
|
|
|
|
|
|
|
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
2018-08-05 14:51:17 +10:00
|
|
|
HOTP::HOTP (cruft::view<const char*> _key, uint64_t _counter):
|
2018-01-14 17:17:34 +11:00
|
|
|
m_counter (_counter),
|
2018-06-01 15:59:01 +10:00
|
|
|
m_hash (_key.template cast<const uint8_t*> ())
|
2018-01-14 17:17:34 +11:00
|
|
|
{ ; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
//-----------------------------------------------------------------------------
|
|
|
|
unsigned
|
|
|
|
HOTP::value (void)
|
|
|
|
{
|
|
|
|
union {
|
|
|
|
uint64_t number;
|
|
|
|
uint8_t bytes[8];
|
|
|
|
};
|
|
|
|
|
2018-08-05 14:51:17 +10:00
|
|
|
number = cruft::htob (m_counter);
|
2018-01-14 17:17:34 +11:00
|
|
|
|
2018-08-05 14:51:17 +10:00
|
|
|
auto res = truncate (m_hash (cruft::make_cview (bytes)));
|
2018-01-14 17:17:34 +11:00
|
|
|
++m_counter;
|
|
|
|
return res % 1'000'000;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
//-----------------------------------------------------------------------------
|
|
|
|
uint32_t
|
|
|
|
HOTP::truncate (SHA1::digest_t d)
|
|
|
|
{
|
|
|
|
// offset into the digest by the last 4 bits
|
|
|
|
size_t o= d[d.size () - 1] & 0x0F;
|
|
|
|
|
|
|
|
// mask the highest bit per the specification
|
|
|
|
uint32_t v = (d[o + 0] & 0x7f) << 24 |
|
|
|
|
(d[o + 1] & 0xff) << 16 |
|
|
|
|
(d[o + 2] & 0xff) << 8 |
|
|
|
|
(d[o + 3] & 0xff) << 0;
|
|
|
|
|
|
|
|
return v;
|
|
|
|
}
|