Gcryptlib: new brace style, and moved to Leonetienne namespace

This commit is contained in:
Leonetienne 2022-05-16 22:15:34 +02:00
parent c551f5fa64
commit acf9dea387
No known key found for this signature in database
GPG Key ID: C33879CD92E9708C
17 changed files with 917 additions and 901 deletions

View File

@ -4,7 +4,7 @@
#include <Util.h> #include <Util.h>
#include <InitializationVector.h> #include <InitializationVector.h>
using namespace GhettoCipher; using namespace Leonetienne::GCrypt;
void ExampleString() { void ExampleString() {
std::cout << "Example on how to encrypt & decrypt a string:" << std::endl; std::cout << "Example on how to encrypt & decrypt a string:" << std::endl;

View File

@ -2,7 +2,7 @@
#include "SecureBitset.h" #include "SecureBitset.h"
#include "Config.h" #include "Config.h"
namespace GhettoCipher { namespace Leonetienne::GCrypt {
typedef SecureBitset<BLOCK_SIZE> Block; typedef SecureBitset<BLOCK_SIZE> Block;
} }

View File

@ -2,7 +2,7 @@
#include "Feistel.h" #include "Feistel.h"
#include "Flexblock.h" #include "Flexblock.h"
namespace GhettoCipher { namespace Leonetienne::GCrypt {
/** Class to apply a block cipher to messages of arbitrary length in a distributed manner /** Class to apply a block cipher to messages of arbitrary length in a distributed manner
*/ */
class Cipher { class Cipher {

View File

@ -1,7 +1,7 @@
#pragma once #pragma once
#include <cstddef> #include <cstddef>
namespace GhettoCipher { namespace Leonetienne::GCrypt {
// MUST BE A POWER OF 2 > 4 // MUST BE A POWER OF 2 > 4
constexpr std::size_t BLOCK_SIZE = 512; constexpr std::size_t BLOCK_SIZE = 512;

View File

@ -3,7 +3,7 @@
#include "Block.h" #include "Block.h"
#include "Halfblock.h" #include "Halfblock.h"
namespace GhettoCipher { namespace Leonetienne::GCrypt {
/** Class to perform a feistel block chipher /** Class to perform a feistel block chipher
*/ */
class Feistel { class Feistel {

View File

@ -1,7 +1,7 @@
#pragma once #pragma once
#include <string> #include <string>
namespace GhettoCipher { namespace Leonetienne::GCrypt {
//! A "bitset" of variable length //! A "bitset" of variable length
typedef std::string Flexblock; typedef std::string Flexblock;
} }

View File

@ -1,9 +1,9 @@
#pragma once #pragma once
#include <string> #include <string>
namespace GhettoCipher { namespace Leonetienne::GCrypt {
/** This class is a wrapper to make working with the GhettoCipher /** This class is a wrapper to make working with the GhettoCipher
* super easy with a python-like syntax * super easy with a python-like syntax
*/ */
class GhettoCryptWrapper { class GhettoCryptWrapper {
public: public:

View File

@ -3,7 +3,7 @@
#include <cstdint> #include <cstdint>
#include "Config.h" #include "Config.h"
namespace GhettoCipher { namespace Leonetienne::GCrypt {
constexpr std::size_t HALFBLOCK_SIZE = (BLOCK_SIZE / 2); constexpr std::size_t HALFBLOCK_SIZE = (BLOCK_SIZE / 2);
typedef SecureBitset<HALFBLOCK_SIZE> Halfblock; typedef SecureBitset<HALFBLOCK_SIZE> Halfblock;
} }

View File

@ -2,16 +2,16 @@
#include "Config.h" #include "Config.h"
#include "Block.h" #include "Block.h"
namespace GhettoCipher { namespace Leonetienne::GCrypt {
/** Will create a sudo-random Block based on a seed /** Will create a sudo-random Block based on a seed
*/ */
class InitializationVector { class InitializationVector {
public: public:
InitializationVector(const GhettoCipher::Block& seed); InitializationVector(const Block& seed);
operator GhettoCipher::Block() const; operator Block() const;
private: private:
GhettoCipher::Block iv; Block iv;
}; };
} }

View File

@ -3,6 +3,6 @@
#include "Block.h" #include "Block.h"
#include "Config.h" #include "Config.h"
namespace GhettoCipher { namespace Leonetienne::GCrypt {
typedef std::array<Block, N_ROUNDS> Keyset; typedef std::array<Block, N_ROUNDS> Keyset;
} }

View File

@ -3,7 +3,7 @@
#include <ostream> #include <ostream>
#include <istream> #include <istream>
namespace GhettoCipher { namespace Leonetienne::GCrypt {
/** Wrapper for std::bitset<T> that zeroes memory upon deletion. /** Wrapper for std::bitset<T> that zeroes memory upon deletion.
* This does not include ALL methods, but the ones needed. * This does not include ALL methods, but the ones needed.
* *

View File

@ -10,7 +10,7 @@
#include "Cipher.h" #include "Cipher.h"
#include "InitializationVector.h" #include "InitializationVector.h"
namespace GhettoCipher { namespace Leonetienne::GCrypt {
//! Mod-operator that works with negative values //! Mod-operator that works with negative values
inline int Mod(const int numerator, const int denominator) { inline int Mod(const int numerator, const int denominator) {
return (denominator + (numerator % denominator)) % denominator; return (denominator + (numerator % denominator)) % denominator;

View File

@ -4,128 +4,132 @@
#include "Util.h" #include "Util.h"
#include "InitializationVector.h" #include "InitializationVector.h"
GhettoCipher::Cipher::Cipher(const Block& key) namespace Leonetienne::GCrypt {
:
key { key },
initializationVector(InitializationVector(key)) {
return; Cipher::Cipher(const Block& key)
} :
key { key },
initializationVector(InitializationVector(key)) {
GhettoCipher::Cipher::Cipher(const std::string& password) return;
:
key { PasswordToKey(password) },
initializationVector(InitializationVector(key)) {
return;
}
GhettoCipher::Cipher::~Cipher() {
// Clear key memory
ZeroKeyMemory();
return;
}
void GhettoCipher::Cipher::SetKey(const Block& key) {
ZeroKeyMemory();
this->key = key;
return;
}
void GhettoCipher::Cipher::SetPassword(const std::string& password) {
ZeroKeyMemory();
key = PasswordToKey(password);
return;
}
GhettoCipher::Flexblock GhettoCipher::Cipher::Encipher(const Flexblock& data, bool printProgress) const {
// Split cleartext into blocks
std::vector<Block> blocks;
for (std::size_t i = 0; i < data.size(); i += BLOCK_SIZE) {
blocks.push_back(Block(
PadStringToLength(data.substr(i, BLOCK_SIZE), BLOCK_SIZE, '0', false))
);
} }
// Encrypt individual blocks using cipher block chaining Cipher::Cipher(const std::string& password)
Feistel feistel(key); :
key { PasswordToKey(password) },
initializationVector(InitializationVector(key)) {
return;
}
for (std::size_t i = 0; i < blocks.size(); i++) { Cipher::~Cipher() {
// Print reports if desired. If we have > 1000 blocks, print one report every 100 blocks. Otherwise for every 10th block. // Clear key memory
if ((i % ((blocks.size() > 1000)? 100 : 10) == 0) && (printProgress)) { ZeroKeyMemory();
std::cout << "Encrypting... (Block " << i << " / " << blocks.size() << " - " << ((float)i*100 / blocks.size()) << "%)" << std::endl;
return;
}
void Cipher::SetKey(const Block& key) {
ZeroKeyMemory();
this->key = key;
return;
}
void Cipher::SetPassword(const std::string& password) {
ZeroKeyMemory();
key = PasswordToKey(password);
return;
}
Flexblock Cipher::Encipher(const Flexblock& data, bool printProgress) const {
// Split cleartext into blocks
std::vector<Block> blocks;
for (std::size_t i = 0; i < data.size(); i += BLOCK_SIZE) {
blocks.push_back(Block(
PadStringToLength(data.substr(i, BLOCK_SIZE), BLOCK_SIZE, '0', false))
);
} }
const Block& lastBlock = (i>0) ? blocks[i-1] : initializationVector; // Encrypt individual blocks using cipher block chaining
blocks[i] = feistel.Encipher(blocks[i] ^ lastBlock); // Xor last cipher block with new clear text block before E() Feistel feistel(key);
}
// Concatenate ciphertext blocks back into a flexblock for (std::size_t i = 0; i < blocks.size(); i++) {
std::stringstream ss; // Print reports if desired. If we have > 1000 blocks, print one report every 100 blocks. Otherwise for every 10th block.
for (Block& b : blocks) { if ((i % ((blocks.size() > 1000)? 100 : 10) == 0) && (printProgress)) {
ss << b; std::cout << "Encrypting... (Block " << i << " / " << blocks.size() << " - " << ((float)i*100 / blocks.size()) << "%)" << std::endl;
} }
// Return it const Block& lastBlock = (i>0) ? blocks[i-1] : initializationVector;
return ss.str(); blocks[i] = feistel.Encipher(blocks[i] ^ lastBlock); // Xor last cipher block with new clear text block before E()
}
GhettoCipher::Flexblock GhettoCipher::Cipher::Decipher(const Flexblock& data, bool printProgress) const {
// Split ciphertext into blocks
std::vector<Block> blocks;
for (std::size_t i = 0; i < data.size(); i += BLOCK_SIZE) {
blocks.push_back(Block(
PadStringToLength(data.substr(i, BLOCK_SIZE), BLOCK_SIZE, '0', false))
);
}
// Decrypt individual blocks
Feistel feistel(key);
// We can't do this in-loop for decryption, because we are decrypting the blocks in-place.
Block lastBlock = initializationVector;
for (std::size_t i = 0; i < blocks.size(); i++) {
// Print reports if desired. If we have > 1000 blocks, print one report every 100 blocks. Otherwise for every 10th block.
if ((i % ((blocks.size() > 1000) ? 100 : 10) == 0) && (printProgress)) {
std::cout << "Decrypting... (Block " << i << " / " << blocks.size() << " - " << ((float)i*100/ blocks.size()) << "%)" << std::endl;
} }
Block tmpCopy = blocks[i]; // Concatenate ciphertext blocks back into a flexblock
std::stringstream ss;
for (Block& b : blocks) {
ss << b;
}
blocks[i] = feistel.Decipher(blocks[i]) ^ lastBlock; // Decipher cipher block [i] and then xor it with the last cipher block [i-1] we've had // Return it
return ss.str();
lastBlock = std::move(tmpCopy);
} }
// Concatenate ciphertext blocks back into a flexblock Flexblock Cipher::Decipher(const Flexblock& data, bool printProgress) const {
std::stringstream ss; // Split ciphertext into blocks
for (Block& b : blocks) { std::vector<Block> blocks;
ss << b;
for (std::size_t i = 0; i < data.size(); i += BLOCK_SIZE) {
blocks.push_back(Block(
PadStringToLength(data.substr(i, BLOCK_SIZE), BLOCK_SIZE, '0', false))
);
}
// Decrypt individual blocks
Feistel feistel(key);
// We can't do this in-loop for decryption, because we are decrypting the blocks in-place.
Block lastBlock = initializationVector;
for (std::size_t i = 0; i < blocks.size(); i++) {
// Print reports if desired. If we have > 1000 blocks, print one report every 100 blocks. Otherwise for every 10th block.
if ((i % ((blocks.size() > 1000) ? 100 : 10) == 0) && (printProgress)) {
std::cout << "Decrypting... (Block " << i << " / " << blocks.size() << " - " << ((float)i*100/ blocks.size()) << "%)" << std::endl;
}
Block tmpCopy = blocks[i];
blocks[i] = feistel.Decipher(blocks[i]) ^ lastBlock; // Decipher cipher block [i] and then xor it with the last cipher block [i-1] we've had
lastBlock = std::move(tmpCopy);
}
// Concatenate ciphertext blocks back into a flexblock
std::stringstream ss;
for (Block& b : blocks) {
ss << b;
}
// Return it
return ss.str();
} }
// Return it // These pragmas only work for MSVC and g++, as far as i know. Beware!!!
return ss.str();
}
// These pragmas only work for MSVC and g++, as far as i know. Beware!!!
#if defined _WIN32 || defined _WIN64 #if defined _WIN32 || defined _WIN64
#pragma optimize("", off ) #pragma optimize("", off )
#elif defined __GNUG__ #elif defined __GNUG__
#pragma GCC push_options #pragma GCC push_options
#pragma GCC optimize ("O0") #pragma GCC optimize ("O0")
#endif #endif
void GhettoCipher::Cipher::ZeroKeyMemory() { void Cipher::ZeroKeyMemory() {
key.reset(); key.reset();
return; return;
} }
#if defined _WIN32 || defined _WIN64 #if defined _WIN32 || defined _WIN64
#pragma optimize("", on ) #pragma optimize("", on )
#elif defined __GNUG__ #elif defined __GNUG__
#pragma GCC pop_options #pragma GCC pop_options
#endif #endif
}

View File

@ -3,258 +3,262 @@
#include "Util.h" #include "Util.h"
#include "Config.h" #include "Config.h"
GhettoCipher::Feistel::Feistel(const Block& key) { namespace Leonetienne::GCrypt {
SetKey(key);
return;
}
GhettoCipher::Feistel::~Feistel() { Feistel::Feistel(const Block& key) {
ZeroKeyMemory(); SetKey(key);
return;
}
return; Feistel::~Feistel() {
} ZeroKeyMemory();
void GhettoCipher::Feistel::SetKey(const Block& key) { return;
GenerateRoundKeys(key); }
return;
}
GhettoCipher::Block GhettoCipher::Feistel::Encipher(const Block& data) { void Feistel::SetKey(const Block& key) {
return Run(data, false); GenerateRoundKeys(key);
} return;
}
GhettoCipher::Block GhettoCipher::Feistel::Decipher(const Block& data) { Block Feistel::Encipher(const Block& data) {
return Run(data, true); return Run(data, false);
} }
GhettoCipher::Block GhettoCipher::Feistel::Run(const Block& data, bool reverseKeys) { Block Feistel::Decipher(const Block& data) {
const auto splitData = FeistelSplit(data); return Run(data, true);
GhettoCipher::Halfblock l = splitData.first; }
GhettoCipher::Halfblock r = splitData.second;
Halfblock tmp; Block Feistel::Run(const Block& data, bool reverseKeys) {
const auto splitData = FeistelSplit(data);
Halfblock l = splitData.first;
Halfblock r = splitData.second;
for (std::size_t i = 0; i < N_ROUNDS; i++) { Halfblock tmp;
// Calculate key index
std::size_t keyIndex;
if (reverseKeys) {
keyIndex = N_ROUNDS - i - 1;
}
else {
keyIndex = i;
}
// Do a feistel round for (std::size_t i = 0; i < N_ROUNDS; i++) {
tmp = r; // Calculate key index
r = l ^ F(r, roundKeys[keyIndex]); std::size_t keyIndex;
l = tmp; if (reverseKeys) {
} keyIndex = N_ROUNDS - i - 1;
}
else {
keyIndex = i;
}
// Block has finished de*ciphering. // Do a feistel round
// Let's generate a new set of round keys. tmp = r;
GenerateRoundKeys((Block)roundKeys.back()); r = l ^ F(r, roundKeys[keyIndex]);
l = tmp;
}
return FeistelCombine(r, l); // Block has finished de*ciphering.
} // Let's generate a new set of round keys.
GenerateRoundKeys((Block)roundKeys.back());
GhettoCipher::Halfblock GhettoCipher::Feistel::F(Halfblock m, const Block& key) { return FeistelCombine(r, l);
// Made-up F function }
// Expand to full bitwidth Halfblock Feistel::F(Halfblock m, const Block& key) {
Block m_expanded = ExpansionFunction(m); // Made-up F function
// Shift to left by 1 // Expand to full bitwidth
m_expanded = Shiftl(m_expanded, 1); Block m_expanded = ExpansionFunction(m);
// Xor with key // Shift to left by 1
m_expanded ^= key; m_expanded = Shiftl(m_expanded, 1);
// Non-linearly apply subsitution boxes // Xor with key
std::stringstream ss; m_expanded ^= key;
const std::string m_str = m_expanded.to_string();
for (std::size_t i = 0; i < BLOCK_SIZE; i += 4) { // Non-linearly apply subsitution boxes
ss << SBox(m_str.substr(i, 4)); std::stringstream ss;
} const std::string m_str = m_expanded.to_string();
m_expanded = Block(ss.str()); for (std::size_t i = 0; i < BLOCK_SIZE; i += 4) {
ss << SBox(m_str.substr(i, 4));
}
// Return the compressed version m_expanded = Block(ss.str());
return CompressionFunction(m_expanded);
}
std::pair<GhettoCipher::Halfblock, GhettoCipher::Halfblock> GhettoCipher::Feistel::FeistelSplit(const Block& block) { // Return the compressed version
const std::string bits = block.to_string(); return CompressionFunction(m_expanded);
}
Halfblock l(bits.substr(0, bits.size() / 2)); std::pair<Halfblock, Halfblock> Feistel::FeistelSplit(const Block& block) {
Halfblock r(bits.substr(bits.size() / 2)); const std::string bits = block.to_string();
return std::make_pair(l, r); Halfblock l(bits.substr(0, bits.size() / 2));
} Halfblock r(bits.substr(bits.size() / 2));
GhettoCipher::Block GhettoCipher::Feistel::FeistelCombine(const Halfblock& l, const Halfblock& r) { return std::make_pair(l, r);
return Block(l.to_string() + r.to_string()); }
}
GhettoCipher::Block GhettoCipher::Feistel::ExpansionFunction(const Halfblock& block) { Block Feistel::FeistelCombine(const Halfblock& l, const Halfblock& r) {
std::stringstream ss; return Block(l.to_string() + r.to_string());
const std::string bits = block.to_string(); }
std::unordered_map<std::string, std::string> expansionMap; Block Feistel::ExpansionFunction(const Halfblock& block) {
expansionMap["00"] = "1101"; std::stringstream ss;
expansionMap["01"] = "1000"; const std::string bits = block.to_string();
expansionMap["10"] = "0010";
expansionMap["11"] = "0111";
// We have to double the bits! std::unordered_map<std::string, std::string> expansionMap;
for (std::size_t i = 0; i < HALFBLOCK_SIZE; i += 2) { expansionMap["00"] = "1101";
const std::string sub = bits.substr(i, 2); expansionMap["01"] = "1000";
ss << expansionMap[sub]; expansionMap["10"] = "0010";
} expansionMap["11"] = "0111";
return Block(ss.str()); // We have to double the bits!
} for (std::size_t i = 0; i < HALFBLOCK_SIZE; i += 2) {
const std::string sub = bits.substr(i, 2);
ss << expansionMap[sub];
}
GhettoCipher::Halfblock GhettoCipher::Feistel::CompressionFunction(const Block& block) { return Block(ss.str());
std::stringstream ss; }
const std::string bits = block.to_string();
std::unordered_map<std::string, std::string> compressionMap; Halfblock Feistel::CompressionFunction(const Block& block) {
compressionMap["0000"] = "10"; std::stringstream ss;
compressionMap["0001"] = "01"; const std::string bits = block.to_string();
compressionMap["0010"] = "10";
compressionMap["0011"] = "10";
compressionMap["0100"] = "11";
compressionMap["0101"] = "01";
compressionMap["0110"] = "00";
compressionMap["0111"] = "11";
compressionMap["1000"] = "01";
compressionMap["1001"] = "00";
compressionMap["1010"] = "11";
compressionMap["1011"] = "00";
compressionMap["1100"] = "11";
compressionMap["1101"] = "10";
compressionMap["1110"] = "00";
compressionMap["1111"] = "01";
// We have to half the bits! std::unordered_map<std::string, std::string> compressionMap;
for (std::size_t i = 0; i < BLOCK_SIZE; i += 4) { compressionMap["0000"] = "10";
const std::string sub = bits.substr(i, 4); compressionMap["0001"] = "01";
ss << compressionMap[sub]; compressionMap["0010"] = "10";
} compressionMap["0011"] = "10";
compressionMap["0100"] = "11";
compressionMap["0101"] = "01";
compressionMap["0110"] = "00";
compressionMap["0111"] = "11";
compressionMap["1000"] = "01";
compressionMap["1001"] = "00";
compressionMap["1010"] = "11";
compressionMap["1011"] = "00";
compressionMap["1100"] = "11";
compressionMap["1101"] = "10";
compressionMap["1110"] = "00";
compressionMap["1111"] = "01";
return Halfblock(ss.str()); // We have to half the bits!
} for (std::size_t i = 0; i < BLOCK_SIZE; i += 4) {
const std::string sub = bits.substr(i, 4);
ss << compressionMap[sub];
}
std::string GhettoCipher::Feistel::SBox(const std::string& in) { return Halfblock(ss.str());
static std::unordered_map<std::string, std::string> subMap; }
static bool mapInitialized = false;
if (!mapInitialized) {
subMap["0000"] = "1100";
subMap["0001"] = "1000";
subMap["0010"] = "0001";
subMap["0011"] = "0111";
subMap["0100"] = "1011";
subMap["0101"] = "0011";
subMap["0110"] = "1101";
subMap["0111"] = "1111";
subMap["1000"] = "0000";
subMap["1001"] = "1010";
subMap["1010"] = "0100";
subMap["1011"] = "1001";
subMap["1100"] = "0010";
subMap["1101"] = "1110";
subMap["1110"] = "0101";
subMap["1111"] = "0110";
mapInitialized = true;
}
return subMap[in]; std::string Feistel::SBox(const std::string& in) {
} static std::unordered_map<std::string, std::string> subMap;
static bool mapInitialized = false;
if (!mapInitialized) {
subMap["0000"] = "1100";
subMap["0001"] = "1000";
subMap["0010"] = "0001";
subMap["0011"] = "0111";
subMap["0100"] = "1011";
subMap["0101"] = "0011";
subMap["0110"] = "1101";
subMap["0111"] = "1111";
subMap["1000"] = "0000";
subMap["1001"] = "1010";
subMap["1010"] = "0100";
subMap["1011"] = "1001";
subMap["1100"] = "0010";
subMap["1101"] = "1110";
subMap["1110"] = "0101";
subMap["1111"] = "0110";
mapInitialized = true;
}
void GhettoCipher::Feistel::GenerateRoundKeys(const Block& seedKey) { return subMap[in];
// Clear initial key memory }
ZeroKeyMemory();
roundKeys = Keyset();
// Derive the initial two round keys void Feistel::GenerateRoundKeys(const Block& seedKey) {
// Clear initial key memory
ZeroKeyMemory();
roundKeys = Keyset();
// Compress- substitute, and expand the seed key to form the initial and the second-initial round key // Derive the initial two round keys
// This action is non-linear and irreversible, and thus strenghtens security.
Halfblock compressedSeed1 = CompressionFunction(seedKey);
Halfblock compressedSeed2 = CompressionFunction(Shiftl(seedKey, 1)); // Shifting one key by 1 will result in a completely different compression
// To add further confusion, let's shift seed1 by 1 aswell (after compression, but before substitution) // Compress- substitute, and expand the seed key to form the initial and the second-initial round key
// but only if the total number of bits set are a multiple of 3 // This action is non-linear and irreversible, and thus strenghtens security.
// if it is a multiple of 4, we'll shift it by 1 into the opposite direction Halfblock compressedSeed1 = CompressionFunction(seedKey);
const std::size_t setBits1 = compressedSeed1.count(); Halfblock compressedSeed2 = CompressionFunction(Shiftl(seedKey, 1)); // Shifting one key by 1 will result in a completely different compression
if (setBits1 % 4 == 0) { // To add further confusion, let's shift seed1 by 1 aswell (after compression, but before substitution)
compressedSeed1 = Shiftr(compressedSeed1, 1); // but only if the total number of bits set are a multiple of 3
} // if it is a multiple of 4, we'll shift it by 1 into the opposite direction
else if (setBits1 % 3 == 0) { const std::size_t setBits1 = compressedSeed1.count();
compressedSeed1 = Shiftl(compressedSeed1, 1);
}
// Now apply substitution if (setBits1 % 4 == 0) {
std::stringstream ssKey1; compressedSeed1 = Shiftr(compressedSeed1, 1);
std::stringstream ssKey2; }
const std::string bitsKey1 = compressedSeed1.to_string(); else if (setBits1 % 3 == 0) {
const std::string bitsKey2 = compressedSeed2.to_string(); compressedSeed1 = Shiftl(compressedSeed1, 1);
}
for (std::size_t i = 0; i < HALFBLOCK_SIZE; i += 4) { // Now apply substitution
ssKey1 << SBox(bitsKey1.substr(i, 4)); std::stringstream ssKey1;
ssKey2 << SBox(bitsKey2.substr(i, 4)); std::stringstream ssKey2;
} const std::string bitsKey1 = compressedSeed1.to_string();
const std::string bitsKey2 = compressedSeed2.to_string();
compressedSeed1 = Halfblock(ssKey1.str()); for (std::size_t i = 0; i < HALFBLOCK_SIZE; i += 4) {
compressedSeed2 = Halfblock(ssKey2.str()); ssKey1 << SBox(bitsKey1.substr(i, 4));
ssKey2 << SBox(bitsKey2.substr(i, 4));
}
// Now extrapolate them to BLOCK_SIZE (key size) again compressedSeed1 = Halfblock(ssKey1.str());
// Xor with the original seed key to get rid of the repititions caused by the expansion compressedSeed2 = Halfblock(ssKey2.str());
roundKeys[0] = ExpansionFunction(compressedSeed1) ^ seedKey;
roundKeys[1] = ExpansionFunction(compressedSeed2) ^ seedKey;
// Now derive all other round keys // Now extrapolate them to BLOCK_SIZE (key size) again
// Xor with the original seed key to get rid of the repititions caused by the expansion
roundKeys[0] = ExpansionFunction(compressedSeed1) ^ seedKey;
roundKeys[1] = ExpansionFunction(compressedSeed2) ^ seedKey;
for (std::size_t i = 2; i < roundKeys.size(); i++) { // Now derive all other round keys
// Initialize new round key with last round key
Block newKey = roundKeys[i - 1];
// Shift to left by how many bits are set, modulo 8 for (std::size_t i = 2; i < roundKeys.size(); i++) {
newKey = Shiftl(newKey, newKey.count() % 8); // This action is irreversible // Initialize new round key with last round key
Block newKey = roundKeys[i - 1];
// Split into two halfblocks, // Shift to left by how many bits are set, modulo 8
// apply F() to one halfblock with rk[i-2], newKey = Shiftl(newKey, newKey.count() % 8); // This action is irreversible
// xor the other one with it
// and put them back together
auto halfkeys = FeistelSplit(newKey);
Halfblock halfkey1 = F(halfkeys.first, roundKeys[i - 2]);
Halfblock halfkey2 = halfkeys.second ^ halfkey1; // I know this is reversible, but it helps to diffuse future round keys.
roundKeys[i] = FeistelCombine(halfkey1, halfkey2); // Split into two halfblocks,
} // apply F() to one halfblock with rk[i-2],
// xor the other one with it
// and put them back together
auto halfkeys = FeistelSplit(newKey);
Halfblock halfkey1 = F(halfkeys.first, roundKeys[i - 2]);
Halfblock halfkey2 = halfkeys.second ^ halfkey1; // I know this is reversible, but it helps to diffuse future round keys.
return; roundKeys[i] = FeistelCombine(halfkey1, halfkey2);
} }
// These pragmas only work for MSVC and g++, as far as i know. Beware!!! return;
}
// These pragmas only work for MSVC and g++, as far as i know. Beware!!!
#if defined _WIN32 || defined _WIN64 #if defined _WIN32 || defined _WIN64
#pragma optimize("", off ) #pragma optimize("", off )
#elif defined __GNUG__ #elif defined __GNUG__
#pragma GCC push_options #pragma GCC push_options
#pragma GCC optimize ("O0") #pragma GCC optimize ("O0")
#endif #endif
void GhettoCipher::Feistel::ZeroKeyMemory() { void Feistel::ZeroKeyMemory() {
for (Block& key : roundKeys) { for (Block& key : roundKeys) {
key.reset(); key.reset();
} }
return; return;
} }
#if defined _WIN32 || defined _WIN64 #if defined _WIN32 || defined _WIN64
#pragma optimize("", on ) #pragma optimize("", on )
#elif defined __GNUG__ #elif defined __GNUG__
#pragma GCC pop_options #pragma GCC pop_options
#endif #endif
}

View File

@ -2,83 +2,87 @@
#include "Cipher.h" #include "Cipher.h"
#include "Util.h" #include "Util.h"
std::string GhettoCipher::GhettoCryptWrapper::EncryptString(const std::string& cleartext, const std::string& password) { namespace Leonetienne::GCrypt {
// Instanciate our cipher and supply a key
const Block key = PasswordToKey(password);
Cipher cipher(key);
// Recode the ascii-string to bits
const Flexblock cleartext_bits = StringToBits(cleartext);
// Encrypt our cleartext bits
const Flexblock ciphertext_bits = cipher.Encipher(cleartext_bits);
// Recode the ciphertext bits to a hex-string
const std::string ciphertext = BitsToHexstring(ciphertext_bits);
// Return it
return ciphertext;
}
std::string GhettoCipher::GhettoCryptWrapper::DecryptString(const std::string& ciphertext, const std::string& password) {
// Instanciate our cipher and supply a key
const Block key = PasswordToKey(password);
Cipher cipher(key);
// Recode the hex-string to bits
const Flexblock ciphertext_bits = HexstringToBits(ciphertext);
// Decrypt the ciphertext bits
const std::string cleartext_bits = cipher.Decipher(ciphertext_bits);
// Recode the cleartext bits to an ascii-string
const std::string cleartext = BitsToString(cleartext_bits);
// Return it
return cleartext;
}
bool GhettoCipher::GhettoCryptWrapper::EncryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport) {
try {
// Read the file to bits
const Flexblock cleartext_bits = ReadFileToBits(filename_in);
std::string GhettoCryptWrapper::EncryptString(const std::string& cleartext, const std::string& password) {
// Instanciate our cipher and supply a key // Instanciate our cipher and supply a key
const Block key = PasswordToKey(password); const Block key = PasswordToKey(password);
Cipher cipher(key); Cipher cipher(key);
// Recode the ascii-string to bits
const Flexblock cleartext_bits = StringToBits(cleartext);
// Encrypt our cleartext bits // Encrypt our cleartext bits
const Flexblock ciphertext_bits = cipher.Encipher(cleartext_bits, printProgressReport); const Flexblock ciphertext_bits = cipher.Encipher(cleartext_bits);
// Write our ciphertext bits to file // Recode the ciphertext bits to a hex-string
WriteBitsToFile(filename_out, ciphertext_bits); const std::string ciphertext = BitsToHexstring(ciphertext_bits);
return true; // Return it
return ciphertext;
} }
catch (std::runtime_error&) {
return false;
}
}
bool GhettoCipher::GhettoCryptWrapper::DecryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport) {
try {
// Read the file to bits
const Flexblock ciphertext_bits = ReadFileToBits(filename_in);
std::string GhettoCryptWrapper::DecryptString(const std::string& ciphertext, const std::string& password) {
// Instanciate our cipher and supply a key // Instanciate our cipher and supply a key
const Block key = PasswordToKey(password); const Block key = PasswordToKey(password);
Cipher cipher(key); Cipher cipher(key);
// Recode the hex-string to bits
const Flexblock ciphertext_bits = HexstringToBits(ciphertext);
// Decrypt the ciphertext bits // Decrypt the ciphertext bits
const Flexblock cleartext_bits = cipher.Decipher(ciphertext_bits, printProgressReport); const std::string cleartext_bits = cipher.Decipher(ciphertext_bits);
// Write our cleartext bits to file // Recode the cleartext bits to an ascii-string
WriteBitsToFile(filename_out, cleartext_bits); const std::string cleartext = BitsToString(cleartext_bits);
return true; // Return it
return cleartext;
} }
catch (std::runtime_error&) {
return false; bool GhettoCryptWrapper::EncryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport) {
try {
// Read the file to bits
const Flexblock cleartext_bits = ReadFileToBits(filename_in);
// Instanciate our cipher and supply a key
const Block key = PasswordToKey(password);
Cipher cipher(key);
// Encrypt our cleartext bits
const Flexblock ciphertext_bits = cipher.Encipher(cleartext_bits, printProgressReport);
// Write our ciphertext bits to file
WriteBitsToFile(filename_out, ciphertext_bits);
return true;
}
catch (std::runtime_error&) {
return false;
}
} }
bool GhettoCryptWrapper::DecryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport) {
try {
// Read the file to bits
const Flexblock ciphertext_bits = ReadFileToBits(filename_in);
// Instanciate our cipher and supply a key
const Block key = PasswordToKey(password);
Cipher cipher(key);
// Decrypt the ciphertext bits
const Flexblock cleartext_bits = cipher.Decipher(ciphertext_bits, printProgressReport);
// Write our cleartext bits to file
WriteBitsToFile(filename_out, cleartext_bits);
return true;
}
catch (std::runtime_error&) {
return false;
}
}
} }

View File

@ -1,13 +1,17 @@
#include "InitializationVector.h" #include "InitializationVector.h"
#include "Feistel.h" #include "Feistel.h"
GhettoCipher::InitializationVector::InitializationVector(const Block& seed) { namespace Leonetienne::GCrypt {
// We'll generate our initialization vector by encrypting our seed with itself as a key
// iv = E(M=seed, K=seed) InitializationVector::InitializationVector(const Block& seed) {
iv = Feistel(seed).Encipher(seed); // We'll generate our initialization vector by encrypting our seed with itself as a key
} // iv = E(M=seed, K=seed)
iv = Feistel(seed).Encipher(seed);
GhettoCipher::InitializationVector::operator GhettoCipher::Block() const { }
return iv;
InitializationVector::operator Block() const {
return iv;
}
} }