Skip to content
Snippets Groups Projects
rand.cc 692 B
#include <vereign/crypto/rand.hh>

#include <openssl/rand.h>
#include <vereign/crypto/errors.hh>

namespace vereign::crypto {

void Rand(bytes::Buffer& buf, std::size_t size) {
  buf.Reserve(size);
  int result = RAND_bytes(buf.end(), size);
  if (result == 0) {
    ERR_clear_error();
    throw Error("crypto rand failed");
  }

  buf.IncSize(size);
}

auto Rand(std::size_t size) -> bytes::Buffer {
  bytes::Buffer buf{size};
  Rand(buf, size);

  return buf;
}

auto RandUint64() -> uint64_t {
  uint64_t x = 0;
  int result = RAND_bytes((uint8_t*) &x, sizeof(x));
  if (result == 0) {
    ERR_clear_error();
    throw Error("crypto rand failed");
  }

  return x;
}

} // vereign::crypto