git.fiddlerwoaroof.com
Raw Blame History
#include <stdio.h>
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <string.h>
#include <time.h>

#include <openssl/hmac.h>
#include <openssl/evp.h>

namespace {
  // done
  unsigned long bytesToInt(const std::string &bytes) {
    unsigned long result = 0;
    auto          byteCount = bytes.size() - 1;
    for (auto byte = bytes.cbegin(); byte < bytes.cend(); byte++, byteCount--) {
      const uint8_t val = static_cast<uint8_t>(*byte);
      result |= val << (byteCount * 8);
    }
    return result;
  }

  //done
  int ipow(int base, int exp) {
    int result = 1;
    while (exp) {
      if (exp & 1) {
        result *= base;
      }
      exp >>= 1;
      base *= base;
    }

    return result;
  }

  //done
  unsigned char *timeToBytes(unsigned long long time, unsigned char *data, size_t data_size) {
    for (int idx = data_size - 1; idx > -1; idx--) {
      unsigned char next_digit = time & 0xff;
      data[idx] = next_digit;
      time >>= 8;
    }

    return data;
  }

  //done
  unsigned long truncate(const std::string &mac) {
    uint8_t offset = static_cast<uint8_t >(mac[19]) & static_cast<uint8_t>(0x0f);
    std::string  offsetBytes = mac.substr(offset, 4);
    return bytesToInt(offsetBytes) & 0x7fffffff;
  }

  std::string hotp(const std::string &key, const unsigned char *data, size_t data_size, const int digits=6) {
  }
  
  std::string generate_token(const std::string &key, const int digits=6) {
    //done
    time_t time_chunk = ::time(nullptr) / 30;

    unsigned char data[8] = {0,0,0,0,0,0,0,0};
    timeToBytes(time_chunk, data, 8);

    return hotp(key, data, 8, digits);
  }
}

int main() 
{
  char key[5] = "\x00\x00\x00\x00";
  std::cout << generate_token(std::string(key, 5)) << std::endl;;

  return 0;
}