Skip to content

Commit

Permalink
Random: implement
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidB137 committed Sep 6, 2024
1 parent c4e446b commit ee136a5
Show file tree
Hide file tree
Showing 4 changed files with 120 additions and 0 deletions.
26 changes: 26 additions & 0 deletions include/kvik/random.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @file random.hpp
* @author Dávid Benko ([email protected])
* @brief Random generator
*
* @copyright Copyright (c) 2024
*
*/

#pragma once

#include <cstdlib>

namespace kvik
{
/**
* @brief Generates `len` truly random bytes in `buf`
*
* Implementation is plaform dependent.
*
* @param buf Buffer
* @param len Length
* @throw kvik::Exception Generation failed
*/
void getRandomBytes(void *buf, size_t len);
} // namespace kvik
20 changes: 20 additions & 0 deletions src/espidf/random.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @file random.cpp
* @author Dávid Benko ([email protected])
* @brief Random generator
*
* @copyright Copyright (c) 2024
*
*/

#include "esp_random.h"

#include "kvik/random.hpp"

namespace kvik
{
void getRandomBytes(void *buf, size_t len)
{
esp_fill_random(buf, len);
}
} // namespace kvik
23 changes: 23 additions & 0 deletions src/linux/random.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* @file random.cpp
* @author Dávid Benko ([email protected])
* @brief Random generator
*
* @copyright Copyright (c) 2024
*
*/

#include <sys/random.h>

#include "kvik/errors.hpp"
#include "kvik/random.hpp"

namespace kvik
{
void getRandomBytes(void *buf, size_t len)
{
if (getrandom(buf, len, 0) != len) {
throw Exception("Generation failed");
}
}
} // namespace kvik
51 changes: 51 additions & 0 deletions test/tests/random.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* @file random.cpp
* @author Dávid Benko ([email protected])
* @copyright Copyright (c) 2024
*/

#include <catch2/catch_test_macros.hpp>

#include "kvik/random.hpp"

using namespace kvik;

TEST_CASE("Simple random bytes", "[Random]")
{
uint64_t n = 0;
REQUIRE_NOTHROW(getRandomBytes(&n, sizeof(n)));
REQUIRE(n != 0);
}

TEST_CASE("Zero length buffer", "[Random]")
{
uint64_t n = 0;
REQUIRE_NOTHROW(getRandomBytes(&n, 0));
REQUIRE(n == 0);
}

TEST_CASE("Long buffer", "[Random]")
{
size_t size = 5e6; // 5 MB

// Allocate big buffer
uint8_t *buf = (uint8_t *)calloc(size, 1);
REQUIRE(buf != nullptr);

// Sum up and check last 100 bytes
uint16_t sum = 0;
for (size_t i = 0; i < 100; i++)
{
sum += buf[size - i - 1];
}
REQUIRE(sum == 0);

REQUIRE_NOTHROW(getRandomBytes(buf, size));

// Sum up and check again
for (size_t i = 0; i < 100; i++)
{
sum += buf[size - i - 1];
}
REQUIRE(sum != 0);
}

0 comments on commit ee136a5

Please sign in to comment.