fortuna/generator.cpp

215 lines
5.1 KiB
C++
Raw Normal View History

#ifndef FORTUNA_GENERATOR_CPP
#define FORTUNA_GENERATOR_CPP
#include "generator.h"
#include "util.h"
2022-01-10 04:25:03 +01:00
#include <cryptopp/ccm.h>
#include <cryptopp/filters.h>
2022-01-10 04:25:03 +01:00
#include <cryptopp/hex.h>
#include <cryptopp/serpent.h>
#include <fmt/core.h>
#include <algorithm>
#include <cassert>
#include <chrono>
2022-01-10 04:25:03 +01:00
#include <cmath>
#include <cstdint>
#include <mutex>
#include <stdexcept>
namespace fortuna {
namespace generator {
Generator::Generator() /*noexcept*/ {
try {
initialize_generator();
2022-01-10 04:25:03 +01:00
}
catch (CryptoPP::Exception& e) {
fmt::print(stderr, "{}\n", e.what());
exit(1);
}
}
2022-01-17 04:03:06 +01:00
Generator::~Generator() noexcept {}
2021-10-19 15:05:18 +02:00
2022-01-10 04:25:03 +01:00
void Generator::initialize_generator() {
try {
std::memset(G.k, 0x00, G.k.size());
G.ctr = 0;
fmt::print("Generator initialized\n");
2022-01-10 04:25:03 +01:00
}
catch (CryptoPP::Exception& e) {
fmt::print(stderr, "{}\n", e.what());
exit(1);
}
2022-01-08 06:34:30 +01:00
}
2022-01-06 16:47:46 +01:00
auto Generator::get_state() const -> G_state {
return G;
}
auto Generator::time_to_reseed(
const uint64_t& pool0_len,
const unsigned int& min_p_size,
const std::chrono::duration<int64_t, std::ratio<1, 1000>>& time_elapsed,
const std::chrono::milliseconds& gen_reseed_interval) const -> bool {
if (pool0_len >= min_p_size && time_elapsed > gen_reseed_interval) {
return true;
2022-01-10 04:25:03 +01:00
}
else {
return false;
}
}
auto Generator::reseed(const std::string& s) -> void {
std::unique_lock<std::mutex> ul(reseed_mtx);
// ref: https://www.cryptopp.com/wiki/SecBlock
std::string da_key(reinterpret_cast<const char*>(&G.k[0]),
2022-01-10 04:25:03 +01:00
G.k.SizeInBytes() * 8); // we need the size in bits
try {
std::string a{fortuna::Util::do_sha(da_key + s)};
2022-01-08 07:06:31 +01:00
std::memmove(G.k, a.c_str(), G.k_length);
++G.ctr;
fmt::print("[i] generator: reseeded\n");
2022-01-10 04:25:03 +01:00
}
catch (std::exception& e) {
fmt::print("{}", e.what());
}
}
auto Generator::do_crypto() -> std::string {
2021-10-19 15:05:18 +02:00
/* this function calls the block cipher
* returns a string of k*(16 bytes);
* do whatever atm */
// for the moment loosely based on
// https://www.cryptopp.com/wiki/CTR_Mode
// William Shakespeare, Romeo and Juliet
std::string plain{"Oh, I am fortune's fool!"};
std::string cipher, encoded_c;
std::unique_lock<std::mutex> ul(crypt_mtx);
// in case we need to convert counter to string
2022-01-08 07:06:31 +01:00
std::string str_ctr{reinterpret_cast<const char*>(&G.ctr)};
// 16 bytes --> 128bit
static constexpr const std::size_t ctr_length{16};
CryptoPP::FixedSizeSecBlock<CryptoPP::byte, ctr_length> ctr;
2022-01-08 07:06:31 +01:00
std::memmove(ctr, str_ctr.c_str(), ctr_length);
try {
CryptoPP::CTR_Mode<CryptoPP::Serpent>::Encryption e;
2022-01-10 04:25:03 +01:00
e.SetKeyWithIV(G.k, G.k.size(), ctr);
ul.unlock();
// The StreamTransformationFilter adds padding as required. ECB and
// CBC Mode must be padded to the block size of the cipher. CTR
// mode not.
// the "true" param - pump all of the data immediately to its
// attached transformation
2022-01-10 04:25:03 +01:00
CryptoPP::StringSource str_src1(
plain,
true,
2022-01-10 04:25:03 +01:00
new CryptoPP::StreamTransformationFilter(
e,
new CryptoPP::StringSink(cipher)) // StreamTransformationFilter
); // StringSource
}
2022-01-10 04:25:03 +01:00
catch (CryptoPP::Exception& e) {
fmt::print(stderr, "{}\n", e.what());
exit(1);
}
// Pretty print cipher text
2022-01-10 04:25:03 +01:00
CryptoPP::StringSource str_src2(
cipher,
true,
new CryptoPP::HexEncoder(
2022-01-10 04:25:03 +01:00
new CryptoPP::StringSink(encoded_c)) // HexEncoder
); // StringSource
return encoded_c;
2021-10-19 15:05:18 +02:00
}
auto Generator::generate_blocks(unsigned int k_blocks) -> std::string {
2022-01-10 04:25:03 +01:00
assert((G.ctr != 0) && "Counter is not 0, generator has been seeded");
2022-01-14 05:40:22 +01:00
std::string r{""};
2022-01-14 05:40:22 +01:00
while (k_blocks--) {
r += Generator::do_crypto();
2021-11-20 20:57:06 +01:00
++G.ctr;
2021-10-19 15:05:18 +02:00
}
return r;
2021-10-19 15:05:18 +02:00
}
2022-01-17 07:22:19 +01:00
auto Generator::generate_random_data(const unsigned int& n) -> std::string {
std::lock_guard<std::mutex> lg(mtx);
if (n == 0) {
// do not do this..?
const std::string msg{"zero bytes requested, bailing\n"};
2022-01-14 05:20:52 +01:00
fmt::print("[*] g: error: {}", msg);
// throw std::invalid_argument(msg);
// TODO(me): throw or not?
// perhaps just return prematurely
return "";
}
// pre-computed 2^20
if (n > 1048576) {
const std::string msg{"n cannot be > 2^20\n"};
fmt::print("[*] error: {}", msg);
throw std::invalid_argument(msg);
2021-10-19 15:05:18 +02:00
}
std::string r;
try {
/* do magic to compute r
* r first-n-bytes(GenerateBlocks(G, ceil(n/16) )) */
unsigned int how_many(
static_cast<unsigned int>(std::ceil(static_cast<double>(n) / 16)));
std::string rr{generate_blocks(how_many)};
fmt::print("rr (output from generate_blocks): {}\n", rr);
// since we're truncating hex, we need to get twice more characters
2022-01-10 04:25:03 +01:00
r = rr.substr(0, n * 0x02ul);
2021-12-11 01:10:14 +01:00
rr.clear();
2022-01-10 04:25:03 +01:00
}
catch (std::exception& e) {
fmt::print("{}", e.what());
}
/* re-key */
try {
std::string nu_G_k{generate_blocks(2)};
// fmt::print("nu_G_k: {}\n", nu_G_k); // debugging
std::string dst;
CryptoPP::HexDecoder decoder;
decoder.Put(reinterpret_cast<CryptoPP::byte*>(nu_G_k.data()),
nu_G_k.size());
decoder.MessageEnd();
dst.resize(G.k_length);
decoder.Get(reinterpret_cast<CryptoPP::byte*>(&dst[0]), dst.size());
2021-12-11 01:10:14 +01:00
nu_G_k.clear();
/* clear out the old key and set a new one */
std::memset(G.k, 0x00, G.k_length);
2022-01-08 07:06:31 +01:00
std::memmove(G.k, dst.c_str(), G.k_length);
2022-01-10 04:25:03 +01:00
}
catch (std::exception& e) {
fmt::print("{}", e.what());
}
return r;
2022-01-03 01:02:05 +01:00
}
2021-10-19 15:05:18 +02:00
} // namespace generator
} // namespace fortuna
#endif