forked from ak-fortuna/fortuna
99 lines
2.4 KiB
C++
99 lines
2.4 KiB
C++
#ifndef FORTUNA_FORTUNA_CPP
|
|
#define FORTUNA_FORTUNA_CPP
|
|
|
|
#include "fortuna.h"
|
|
|
|
#include <cryptopp/osrng.h>
|
|
#include <cryptopp/hex.h>
|
|
#include <cryptopp/filters.h>
|
|
#include <cryptopp/serpent.h>
|
|
#include <cryptopp/ccm.h>
|
|
#include <fmt/core.h>
|
|
|
|
#include <cassert>
|
|
#include <cstring>
|
|
|
|
|
|
namespace fortuna {
|
|
Fortuna::Fortuna(){
|
|
}
|
|
Fortuna::~Fortuna() = default;
|
|
|
|
auto Fortuna::random_data(unsigned int n_blocks) -> void {
|
|
// for the moment loosely based on
|
|
// https://www.cryptopp.com/wiki/CTR_Mode
|
|
using CryptoPP::StringSource;
|
|
using CryptoPP::StringSink;
|
|
using CryptoPP::HexEncoder;
|
|
using CryptoPP::StreamTransformationFilter;
|
|
using CryptoPP::Serpent;
|
|
using CryptoPP::CTR_Mode;
|
|
|
|
CryptoPP::AutoSeededRandomPool prng;
|
|
// use 256bit key
|
|
CryptoPP::SecByteBlock key(CryptoPP::Serpent::MAX_KEYLENGTH);
|
|
|
|
prng.GenerateBlock(key,key.size());
|
|
|
|
CryptoPP::byte ctr[Serpent::BLOCKSIZE];
|
|
prng.GenerateBlock(ctr,sizeof(ctr));
|
|
|
|
// William Shakespeare, Romeo and Juliet
|
|
std::string plain{"Oh, I am fortune's fool!"};
|
|
std::string cipher, encoded_c, decrypted;
|
|
|
|
try {
|
|
fmt::print("plain text: {}\n", plain);
|
|
|
|
CTR_Mode<Serpent>::Encryption e;
|
|
e.SetKeyWithIV(key,key.size(),ctr);
|
|
|
|
// 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
|
|
StringSource str_src1(plain,true,
|
|
new StreamTransformationFilter(e,
|
|
new StringSink(cipher)
|
|
) // StreamTransformationFilter
|
|
); // StringSource
|
|
}
|
|
catch(CryptoPP::Exception& e) {
|
|
fmt::print(stderr, "{}\n", e.what());
|
|
exit(1);
|
|
}
|
|
|
|
// Pretty print cipher text
|
|
StringSource str_src2(cipher,true,
|
|
new HexEncoder(
|
|
new StringSink(encoded_c)
|
|
) // HexEncoder
|
|
); // StringSource
|
|
fmt::print("cipher text: {}\n", encoded_c);
|
|
|
|
try {
|
|
CTR_Mode<Serpent>::Decryption d;
|
|
d.SetKeyWithIV(key,key.size(),ctr);
|
|
|
|
// The StreamTransformationFilter removes padding as required.
|
|
StringSource str_src3(cipher, true,
|
|
new StreamTransformationFilter(d,
|
|
new StringSink(decrypted)
|
|
) // StreamTransformationFilter
|
|
); // StringSource
|
|
|
|
fmt::print("decrypted text: {}\n", decrypted);
|
|
}
|
|
catch(CryptoPP::Exception& e) {
|
|
fmt::print(stderr, "{}\n", e.what());
|
|
exit(1);
|
|
}
|
|
|
|
|
|
} //random_data
|
|
|
|
} // namespace fortuna
|
|
|
|
#endif//FORTUNA_FORTUNA_CPP
|