Implemented a Key::Random() method

This commit is contained in:
Leonetienne 2022-05-22 17:24:56 +02:00
parent 04c67436c4
commit a3c04b957f
No known key found for this signature in database
GPG Key ID: C33879CD92E9708C
2 changed files with 25 additions and 0 deletions

View File

@ -11,7 +11,12 @@ namespace Leonetienne::GCrypt {
*/ */
class Key : public Block { class Key : public Block {
public: public:
//! Will generate a key from a password
static Key FromPassword(const std::string& password); static Key FromPassword(const std::string& password);
//! Will generate a random key from actual randomness (std::random_device)
static Key Random();
Key(); Key();
Key(const Key& k); Key(const Key& k);
Key(const Block& b); Key(const Block& b);

View File

@ -1,6 +1,8 @@
#include "GCrypt/Key.h" #include "GCrypt/Key.h"
#include "GCrypt/GHash.h" #include "GCrypt/GHash.h"
#include "GCrypt/Util.h" #include "GCrypt/Util.h"
#include <random>
#include <cassert>
namespace Leonetienne::GCrypt { namespace Leonetienne::GCrypt {
@ -10,6 +12,24 @@ namespace Leonetienne::GCrypt {
); );
} }
Key Key::Random() {
// Create our truly-random rng
std::random_device rng;
constexpr std::size_t bitsPerCall = sizeof(std::random_device::result_type) * 8;
// Fetch BLOCK_SIZE bits
std::stringstream ss;
for (std::size_t i = 0; i < BLOCK_SIZE / bitsPerCall; i++) {
ss << std::bitset<bitsPerCall>(rng());
}
// Verify that we actually have the correct size
assert(ss.str().length() == BLOCK_SIZE);
// Return them as a key
return Key(Block(ss.str()));
}
Key::Key() : Block() { Key::Key() : Block() {
} }