libcruft-crypto/hash/hotp.cpp

58 lines
1.4 KiB
C++

/*
* 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/.
*
* Copyright 2015-2018 Danny Robson <danny@nerdcruft.net>
*/
#include "hotp.hpp"
#include <cruft/util/endian.hpp>
#include <cstring>
using cruft::crypto::hash::HOTP;
///////////////////////////////////////////////////////////////////////////////
HOTP::HOTP (util::view<const char*> _key, uint64_t _counter):
m_counter (_counter),
m_hash (_key.template cast<const uint8_t*> ())
{ ; }
//-----------------------------------------------------------------------------
unsigned
HOTP::value (void)
{
union {
uint64_t number;
uint8_t bytes[8];
};
number = util::htob (m_counter);
auto res = truncate (m_hash (util::make_cview (bytes)));
++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;
}