retabbed gcryptlib

This commit is contained in:
Leonetienne 2022-05-16 22:01:52 +02:00
parent ae276e49af
commit c551f5fa64
No known key found for this signature in database
GPG Key ID: C33879CD92E9708C
17 changed files with 576 additions and 662 deletions

View File

@ -1,4 +1,3 @@
#pragma once
#include <iostream> #include <iostream>
#include <GhettoCryptWrapper.h> #include <GhettoCryptWrapper.h>
#include <SecureBitset.h> #include <SecureBitset.h>
@ -7,42 +6,40 @@
using namespace GhettoCipher; using namespace GhettoCipher;
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;
// Get some string // Get some string
const std::string input = "I am a super secret message!"; const std::string input = "I am a super secret message!";
std::cout << input << std::endl; std::cout << input << std::endl;
// Encrypt // Encrypt
const std::string encrypted = GhettoCryptWrapper::EncryptString(input, "password1"); const std::string encrypted = GhettoCryptWrapper::EncryptString(input, "password1");
std::cout << encrypted << std::endl; std::cout << encrypted << std::endl;
// Decrypt
const std::string decrypted = GhettoCryptWrapper::DecryptString(encrypted, "password1");
std::cout << decrypted << std::endl;
return; // Decrypt
const std::string decrypted = GhettoCryptWrapper::DecryptString(encrypted, "password1");
std::cout << decrypted << std::endl;
return;
} }
void ExampleFiles() void ExampleFiles() {
{ std::cout << "Example on how to encrypt & decrypt any file:" << std::endl;
std::cout << "Example on how to encrypt & decrypt any file:" << std::endl;
// Encrypt // Encrypt
GhettoCryptWrapper::EncryptFile("main.cpp", "main.cpp.crypt", "password1"); GhettoCryptWrapper::EncryptFile("main.cpp", "main.cpp.crypt", "password1");
// Decrypt // Decrypt
GhettoCryptWrapper::DecryptFile("main.cpp.crypt", "main.cpp.clear", "password1"); GhettoCryptWrapper::DecryptFile("main.cpp.crypt", "main.cpp.clear", "password1");
return; return;
} }
int main() int main() {
{ ExampleString();
ExampleString(); //ExampleFiles();
//ExampleFiles();
return 0; return 0;
} }

View File

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

View File

@ -37,4 +37,3 @@ namespace GhettoCipher {
Block initializationVector; Block initializationVector;
}; };
} }

View File

@ -8,4 +8,3 @@ namespace GhettoCipher {
// MUST BE > 2 // MUST BE > 2
constexpr std::size_t N_ROUNDS = 64; constexpr std::size_t N_ROUNDS = 64;
} }

View File

@ -3,58 +3,57 @@
#include "Block.h" #include "Block.h"
#include "Halfblock.h" #include "Halfblock.h"
namespace GhettoCipher namespace GhettoCipher {
{ /** Class to perform a feistel block chipher
/** Class to perform a feistel block chipher */
*/ class Feistel {
class Feistel public:
{ explicit Feistel(const Block& key);
public:
explicit Feistel(const Block& key);
Feistel(const Feistel& other) = delete; Feistel(const Feistel& other) = delete;
Feistel(Feistel&& other) noexcept = delete; Feistel(Feistel&& other) noexcept = delete;
~Feistel(); ~Feistel();
//! Will set the seed-key for this feistel network. //! Will set the seed-key for this feistel network.
//! Roundkeys will be derived from this. //! Roundkeys will be derived from this.
void SetKey(const Block& key); void SetKey(const Block& key);
//! Will encipher a data block via the set seed-key //! Will encipher a data block via the set seed-key
Block Encipher(const Block& data); Block Encipher(const Block& data);
//! Will decipher a data block via the set seed-key //! Will decipher a data block via the set seed-key
Block Decipher(const Block& data); Block Decipher(const Block& data);
private: private:
//! Will run the feistel rounds, with either regular key order or reversed key order //! Will run the feistel rounds, with either regular key
Block Run(const Block& data, bool reverseKeys); //! order or reversed key order
Block Run(const Block& data, bool reverseKeys);
//! Arbitrary cipher function //! Arbitrary cipher function
static Halfblock F(Halfblock m, const Block& key); static Halfblock F(Halfblock m, const Block& key);
//! Split a data block into two half blocks (into L and R) //! Split a data block into two half blocks (into L and R)
static std::pair<Halfblock, Halfblock> FeistelSplit(const Block& block); static std::pair<Halfblock, Halfblock> FeistelSplit(const Block& block);
//! Combine two half blocks (L and R) into a regular data block //! Combine two half blocks (L and R) into a regular data block
static Block FeistelCombine(const Halfblock& l, const Halfblock& r); static Block FeistelCombine(const Halfblock& l, const Halfblock& r);
//! Will expand a halfblock to a fullblock //! Will expand a halfblock to a fullblock
static Block ExpansionFunction(const Halfblock& block); static Block ExpansionFunction(const Halfblock& block);
//! Will compress a fullblock to a halfblock //! Will compress a fullblock to a halfblock
static Halfblock CompressionFunction(const Block& block); static Halfblock CompressionFunction(const Block& block);
//! Substitutes four bits by static random others //! Substitutes four bits by static random others
static std::string SBox(const std::string& in); static std::string SBox(const std::string& in);
//! Will generate a the round keys //! Will generate a the round keys
void GenerateRoundKeys(const Block& seedKey); void GenerateRoundKeys(const Block& seedKey);
//! Will zero the memory used by the keyset //! Will zero the memory used by the keyset
void ZeroKeyMemory(); void ZeroKeyMemory();
Keyset roundKeys; Keyset roundKeys;
}; };
} }

View File

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

View File

@ -1,33 +1,32 @@
#pragma once #pragma once
#include <string> #include <string>
namespace GhettoCipher namespace GhettoCipher {
{ /** 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: //! Will encrypt a string and return it hexadecimally encoded.
//! Will encrypt a string and return it hexadecimally encoded. static std::string EncryptString(const std::string& cleartext, const std::string& password);
static std::string EncryptString(const std::string& cleartext, const std::string& password);
//! Will decrypt a hexadecimally encoded string. //! Will decrypt a hexadecimally encoded string.
static std::string DecryptString(const std::string& ciphertext, const std::string& password); static std::string DecryptString(const std::string& ciphertext, const std::string& password);
//! Will encrypt a file. //! Will encrypt a file.
//! Returns false if anything goes wrong (like, file-access). //! Returns false if anything goes wrong (like, file-access).
//! @filename_in The file to be read. //! @filename_in The file to be read.
//! @filename_out The file the encrypted version should be saved in. //! @filename_out The file the encrypted version should be saved in.
static bool EncryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport = false); static bool EncryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport = false);
//! Will decrypt a file. //! Will decrypt a file.
//! Returns false if anything goes wrong (like, file-access). //! Returns false if anything goes wrong (like, file-access).
//! @filename_in The file to be read. //! @filename_in The file to be read.
//! @filename_out The file the decrypted version should be saved in. //! @filename_out The file the decrypted version should be saved in.
static bool DecryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport = false); static bool DecryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport = false);
private: private:
// No instanciation! >:( // No instanciation! >:(
GhettoCryptWrapper(); GhettoCryptWrapper();
}; };
} }

View File

@ -3,8 +3,7 @@
#include <cstdint> #include <cstdint>
#include "Config.h" #include "Config.h"
namespace GhettoCipher namespace GhettoCipher {
{ 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,18 +2,16 @@
#include "Config.h" #include "Config.h"
#include "Block.h" #include "Block.h"
namespace GhettoCipher namespace GhettoCipher {
{ /** 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:
{ InitializationVector(const GhettoCipher::Block& seed);
public:
InitializationVector(const GhettoCipher::Block& seed);
operator GhettoCipher::Block() const; operator GhettoCipher::Block() const;
private: private:
GhettoCipher::Block iv; GhettoCipher::Block iv;
}; };
} }

View File

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

View File

@ -3,322 +3,284 @@
#include <ostream> #include <ostream>
#include <istream> #include <istream>
namespace GhettoCipher namespace GhettoCipher {
{ /** 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. *
* * Just creating a specialization of std::bitset<T> does not work.
* Just creating a specialization of std::bitset<T> does not work. */
*/ template <std::size_t T>
template <std::size_t T> class SecureBitset {
class SecureBitset public:
{ explicit SecureBitset();
public: explicit SecureBitset(const std::string& str);
explicit SecureBitset(); explicit SecureBitset(const long long int i);
explicit SecureBitset(const std::string& str);
explicit SecureBitset(const long long int i);
~SecureBitset(); ~SecureBitset();
bool operator==(const SecureBitset<T>& other) const; bool operator==(const SecureBitset<T>& other) const;
bool operator!=(const SecureBitset<T>& other) const; bool operator!=(const SecureBitset<T>& other) const;
bool operator[](const std::size_t) const; bool operator[](const std::size_t) const;
bool test(const std::size_t index) const; bool test(const std::size_t index) const;
bool all() const; bool all() const;
bool any() const; bool any() const;
bool none() const; bool none() const;
std::size_t count() const; std::size_t count() const;
std::size_t size() const; std::size_t size() const;
SecureBitset<T>& operator&=(const SecureBitset<T>& other); SecureBitset<T>& operator&=(const SecureBitset<T>& other);
SecureBitset<T>& operator|=(const SecureBitset<T>& other); SecureBitset<T>& operator|=(const SecureBitset<T>& other);
SecureBitset<T>& operator^=(const SecureBitset<T>& other); SecureBitset<T>& operator^=(const SecureBitset<T>& other);
SecureBitset<T> operator&(const SecureBitset<T>& other); SecureBitset<T> operator&(const SecureBitset<T>& other);
SecureBitset<T> operator|(const SecureBitset<T>& other); SecureBitset<T> operator|(const SecureBitset<T>& other);
SecureBitset<T> operator^(const SecureBitset<T>& other); SecureBitset<T> operator^(const SecureBitset<T>& other);
SecureBitset<T> operator~() const; SecureBitset<T> operator~() const;
SecureBitset<T>& operator<<=(const std::size_t offset); SecureBitset<T>& operator<<=(const std::size_t offset);
SecureBitset<T>& operator>>=(const std::size_t offset); SecureBitset<T>& operator>>=(const std::size_t offset);
SecureBitset<T> operator<<(const std::size_t offset) const; SecureBitset<T> operator<<(const std::size_t offset) const;
SecureBitset<T> operator>>(const std::size_t offset) const; SecureBitset<T> operator>>(const std::size_t offset) const;
SecureBitset<T>& set(); SecureBitset<T>& set();
SecureBitset<T>& set(const std::size_t index, bool value = true); SecureBitset<T>& set(const std::size_t index, bool value = true);
SecureBitset<T>& reset(); SecureBitset<T>& reset();
SecureBitset<T>& reset(const std::size_t index); SecureBitset<T>& reset(const std::size_t index);
SecureBitset<T>& flip(); SecureBitset<T>& flip();
SecureBitset<T>& flip(const std::size_t index); SecureBitset<T>& flip(const std::size_t index);
std::string to_string() const; std::string to_string() const;
unsigned long to_ulong() const; unsigned long to_ulong() const;
unsigned long long to_ullong() const; unsigned long long to_ullong() const;
std::bitset<T>& Get(); std::bitset<T>& Get();
const std::bitset<T>& Get() const; const std::bitset<T>& Get() const;
private: private:
std::bitset<T> bitset; std::bitset<T> bitset;
}; };
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>::SecureBitset() inline SecureBitset<T>::SecureBitset()
: :
bitset() bitset() {
{ return;
return; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>::SecureBitset(const std::string& str) inline SecureBitset<T>::SecureBitset(const std::string& str)
: :
bitset(str) bitset(str) {
{ return;
return; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>::SecureBitset(const long long int i) inline SecureBitset<T>::SecureBitset(const long long int i)
: :
bitset(i) bitset(i) {
{ return;
return; }
}
// Don't optimize the destructor out!!! // Don't optimize the destructor out!!!
// These pragmas only work for MSVC and g++, as far as i know. Beware!!! // 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
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>::~SecureBitset() inline SecureBitset<T>::~SecureBitset() {
{ bitset.reset();
bitset.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
template<std::size_t T> template<std::size_t T>
inline bool SecureBitset<T>::operator==(const SecureBitset<T>& other) const inline bool SecureBitset<T>::operator==(const SecureBitset<T>& other) const {
{ return bitset == other.bitset;
return bitset == other.bitset; }
}
template<std::size_t T> template<std::size_t T>
inline bool SecureBitset<T>::operator!=(const SecureBitset<T>& other) const inline bool SecureBitset<T>::operator!=(const SecureBitset<T>& other) const {
{ return bitset != other.bitset;
return bitset != other.bitset; }
}
template<std::size_t T> template<std::size_t T>
inline bool SecureBitset<T>::operator[](const std::size_t index) const inline bool SecureBitset<T>::operator[](const std::size_t index) const {
{ return bitset[index];
return bitset[index]; }
}
template<std::size_t T> template<std::size_t T>
inline bool SecureBitset<T>::test(const std::size_t index) const inline bool SecureBitset<T>::test(const std::size_t index) const {
{ return bitset.test(index);
return bitset.test(index); }
}
template<std::size_t T> template<std::size_t T>
inline bool SecureBitset<T>::all() const inline bool SecureBitset<T>::all() const {
{ return bitset.all();
return bitset.all(); }
}
template<std::size_t T> template<std::size_t T>
inline bool SecureBitset<T>::any() const inline bool SecureBitset<T>::any() const {
{ return bitset.any();
return bitset.any(); }
}
template<std::size_t T> template<std::size_t T>
inline bool SecureBitset<T>::none() const inline bool SecureBitset<T>::none() const {
{ return bitset.none();
return bitset.none(); }
}
template<std::size_t T> template<std::size_t T>
inline std::size_t SecureBitset<T>::count() const inline std::size_t SecureBitset<T>::count() const {
{ return bitset.count();
return bitset.count(); }
}
template<std::size_t T> template<std::size_t T>
inline std::size_t SecureBitset<T>::size() const inline std::size_t SecureBitset<T>::size() const {
{ return bitset.count();
return bitset.count(); }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::operator&=(const SecureBitset<T>& other) inline SecureBitset<T>& SecureBitset<T>::operator&=(const SecureBitset<T>& other) {
{ bitset &= other.bitset;
bitset &= other.bitset; return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::operator|=(const SecureBitset<T>& other) inline SecureBitset<T>& SecureBitset<T>::operator|=(const SecureBitset<T>& other) {
{ bitset |= other.bitset;
bitset |= other.bitset; return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::operator^=(const SecureBitset<T>& other) inline SecureBitset<T>& SecureBitset<T>::operator^=(const SecureBitset<T>& other) {
{ bitset ^= other.bitset;
bitset ^= other.bitset; return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T> SecureBitset<T>::operator&(const SecureBitset<T>& other) inline SecureBitset<T> SecureBitset<T>::operator&(const SecureBitset<T>& other) {
{ SecureBitset bs;
SecureBitset bs; bs.bitset = bitset & other.bitset;
bs.bitset = bitset & other.bitset; return bs;
return bs; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T> SecureBitset<T>::operator|(const SecureBitset<T>& other) inline SecureBitset<T> SecureBitset<T>::operator|(const SecureBitset<T>& other) {
{ SecureBitset bs;
SecureBitset bs; bs.bitset = bitset | other.bitset;
bs.bitset = bitset | other.bitset; return bs;
return bs; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T> SecureBitset<T>::operator^(const SecureBitset<T>& other) inline SecureBitset<T> SecureBitset<T>::operator^(const SecureBitset<T>& other) {
{ SecureBitset bs;
SecureBitset bs; bs.bitset = bitset ^ other.bitset;
bs.bitset = bitset ^ other.bitset; return bs;
return bs; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T> SecureBitset<T>::operator~() const inline SecureBitset<T> SecureBitset<T>::operator~() const {
{ SecureBitset bs;
SecureBitset bs; bs.bitset = ~bitset;
bs.bitset = ~bitset; return bs;
return bs; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::operator<<=(const std::size_t offset) inline SecureBitset<T>& SecureBitset<T>::operator<<=(const std::size_t offset) {
{ bitset <<= offset;
bitset <<= offset; return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::operator>>=(const std::size_t offset) inline SecureBitset<T>& SecureBitset<T>::operator>>=(const std::size_t offset) {
{ bitset >>= offset;
bitset >>= offset; return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T> SecureBitset<T>::operator<<(const std::size_t offset) const inline SecureBitset<T> SecureBitset<T>::operator<<(const std::size_t offset) const {
{ SecureBitset bs;
SecureBitset bs; bs.bitset = bitset << offset;
bs.bitset = bitset << offset; return bs;
return bs; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T> SecureBitset<T>::operator>>(const std::size_t offset) const inline SecureBitset<T> SecureBitset<T>::operator>>(const std::size_t offset) const {
{ SecureBitset bs;
SecureBitset bs; bs.bitset = bitset >> offset;
bs.bitset = bitset >> offset; return bs;
return bs; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::set() inline SecureBitset<T>& SecureBitset<T>::set() {
{ bitset.set();
bitset.set(); return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::set(const std::size_t index, bool value) inline SecureBitset<T>& SecureBitset<T>::set(const std::size_t index, bool value) {
{ bitset.set(index, value);
bitset.set(index, value); return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::reset() inline SecureBitset<T>& SecureBitset<T>::reset() {
{ bitset.reset();
bitset.reset(); return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::reset(const std::size_t index) inline SecureBitset<T>& SecureBitset<T>::reset(const std::size_t index) {
{ bitset.reset(index);
bitset.reset(index); return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::flip() inline SecureBitset<T>& SecureBitset<T>::flip() {
{ bitset.flip();
bitset.flip(); return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline SecureBitset<T>& SecureBitset<T>::flip(const std::size_t index) inline SecureBitset<T>& SecureBitset<T>::flip(const std::size_t index) {
{ bitset.flip(index);
bitset.flip(index); return *this;
return *this; }
}
template<std::size_t T> template<std::size_t T>
inline std::string SecureBitset<T>::to_string() const inline std::string SecureBitset<T>::to_string() const {
{ return bitset.to_string();
return bitset.to_string(); }
}
template<std::size_t T> template<std::size_t T>
inline unsigned long SecureBitset<T>::to_ulong() const inline unsigned long SecureBitset<T>::to_ulong() const {
{ return bitset.to_ulong();
return bitset.to_ulong(); }
}
template<std::size_t T>
inline unsigned long long SecureBitset<T>::to_ullong() const
{
return bitset.to_ullong();
}
template<std::size_t T> template<std::size_t T>
inline std::bitset<T>& SecureBitset<T>::Get() inline unsigned long long SecureBitset<T>::to_ullong() const {
{ return bitset.to_ullong();
return bitset; }
}
template<std::size_t T> template<std::size_t T>
inline const std::bitset<T>& SecureBitset<T>::Get() const inline std::bitset<T>& SecureBitset<T>::Get() {
{ return bitset;
return bitset; }
}
template <std::size_t T> template<std::size_t T>
inline std::ostream& operator<<(std::ostream& ofs, const SecureBitset<T>& bs) inline const std::bitset<T>& SecureBitset<T>::Get() const {
{ return bitset;
return ofs << bs.Get(); }
}
template <std::size_t T> template <std::size_t T>
inline std::istream& operator>>(std::istream& ifs, const SecureBitset<T>& bs) inline std::ostream& operator<<(std::ostream& ofs, const SecureBitset<T>& bs) {
{ return ofs << bs.Get();
return ifs >> bs.Get(); }
}
template <std::size_t T>
inline std::istream& operator>>(std::istream& ifs, const SecureBitset<T>& bs) {
return ifs >> bs.Get();
}
} }

View File

@ -10,109 +10,104 @@
#include "Cipher.h" #include "Cipher.h"
#include "InitializationVector.h" #include "InitializationVector.h"
namespace GhettoCipher namespace GhettoCipher {
{
//! 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;
} }
//! Will perform a wrapping left-bitshift on a bitset //! Will perform a wrapping left-bitshift on a bitset
template <std::size_t T> template <std::size_t T>
inline SecureBitset<T> Shiftl(const SecureBitset<T>& bits, const std::size_t amount) inline SecureBitset<T> Shiftl(const SecureBitset<T>& bits, const std::size_t amount) {
{
std::stringstream ss; std::stringstream ss;
const std::string bitss = bits.to_string(); const std::string bitss = bits.to_string();
for (std::size_t i = 0; i < bitss.size(); i++) for (std::size_t i = 0; i < bitss.size(); i++) {
ss << bitss[Mod((int)(i + amount), (int)bitss.size())]; ss << bitss[Mod((int)(i + amount), (int)bitss.size())];
}
return SecureBitset<T>(ss.str()); return SecureBitset<T>(ss.str());
} }
//! Will perform a wrapping right-bitshift on a bitset //! Will perform a wrapping right-bitshift on a bitset
template <std::size_t T> template <std::size_t T>
inline SecureBitset<T> Shiftr(const SecureBitset<T>& bits, const std::size_t amount) inline SecureBitset<T> Shiftr(const SecureBitset<T>& bits, const std::size_t amount) {
{
std::stringstream ss; std::stringstream ss;
const std::string bitss = bits.to_string(); const std::string bitss = bits.to_string();
for (std::size_t i = 0; i < bitss.size(); i++) for (std::size_t i = 0; i < bitss.size(); i++) {
ss << bitss[Mod((i - amount), bitss.size())]; ss << bitss[Mod((i - amount), bitss.size())];
}
return SecureBitset<T>(ss.str()); return SecureBitset<T>(ss.str());
} }
//! Will pad a string to a set length with a certain character //! Will pad a string to a set length with a certain character
inline std::string PadStringToLength(const std::string& str, const std::size_t len, const char pad, const bool padLeft = true) inline std::string PadStringToLength(const std::string& str, const std::size_t len, const char pad, const bool padLeft = true) {
{
// Fast-reject: Already above padded length // Fast-reject: Already above padded length
if (str.length() >= len) if (str.length() >= len) {
return str; return str;
}
std::stringstream ss; std::stringstream ss;
// Pad left: // Pad left:
if (padLeft) if (padLeft) {
{ for (std::size_t i = 0; i < len - str.size(); i++) {
for (std::size_t i = 0; i < len - str.size(); i++)
ss << pad; ss << pad;
}
ss << str; ss << str;
} }
// Pad right: // Pad right:
else else {
{
ss << str; ss << str;
for (std::size_t i = 0; i < len - str.size(); i++) for (std::size_t i = 0; i < len - str.size(); i++) {
ss << pad; ss << pad;
}
} }
return ss.str(); return ss.str();
} }
//! Will convert a string to a fixed-size data block //! Will convert a string to a fixed-size data block
inline Block StringToBitblock(const std::string& s) inline Block StringToBitblock(const std::string& s) {
{
std::stringstream ss; std::stringstream ss;
for (std::size_t i = 0; i < s.size(); i++) for (std::size_t i = 0; i < s.size(); i++) {
ss << std::bitset<8>(s[i]); ss << std::bitset<8>(s[i]);
}
// Pad rest with zeores // Pad rest with zeores
return Block(PadStringToLength(ss.str(), 128, '0', false)); return Block(PadStringToLength(ss.str(), 128, '0', false));
} }
//! Will convert a string to a flexible data block //! Will convert a string to a flexible data block
inline Flexblock StringToBits(const std::string& s) inline Flexblock StringToBits(const std::string& s) {
{
std::stringstream ss; std::stringstream ss;
for (std::size_t i = 0; i < s.size(); i++) for (std::size_t i = 0; i < s.size(); i++) {
ss << std::bitset<8>(s[i]); ss << std::bitset<8>(s[i]);
}
return Flexblock(ss.str()); return Flexblock(ss.str());
} }
//! Will convert a fixed-size data block to a bytestring //! Will convert a fixed-size data block to a bytestring
inline std::string BitblockToBytes(const Block& bits) inline std::string BitblockToBytes(const Block& bits) {
{
std::stringstream ss; std::stringstream ss;
const std::string bitstring = bits.to_string(); const std::string bitstring = bits.to_string();
for (std::size_t i = 0; i < BLOCK_SIZE; i += 8) for (std::size_t i = 0; i < BLOCK_SIZE; i += 8) {
{
ss << (char)std::bitset<8>(bitstring.substr(i, 8)).to_ulong(); ss << (char)std::bitset<8>(bitstring.substr(i, 8)).to_ulong();
} }
return ss.str(); return ss.str();
} }
//! Will convert a fixed-size data block to a string //! Will convert a fixed-size data block to a string
//! The difference to BitblockToBytes() is, that it strips excess nullbytes //! The difference to BitblockToBytes() is, that it strips excess nullbytes
inline std::string BitblockToString(const Block& bits) inline std::string BitblockToString(const Block& bits) {
{
// Decode to bytes // Decode to bytes
std::string text = BitblockToBytes(bits); std::string text = BitblockToBytes(bits);
@ -123,14 +118,12 @@ namespace GhettoCipher
} }
//! Will convert a flexible data block to a bytestring //! Will convert a flexible data block to a bytestring
inline std::string BitsToBytes(const Flexblock& bits) inline std::string BitsToBytes(const Flexblock& bits) {
{
std::stringstream ss; std::stringstream ss;
const std::string bitstring = bits; const std::string bitstring = bits;
for (std::size_t i = 0; i < bits.size(); i += 8) for (std::size_t i = 0; i < bits.size(); i += 8) {
{
ss << (char)std::bitset<8>(bitstring.substr(i, 8)).to_ulong(); ss << (char)std::bitset<8>(bitstring.substr(i, 8)).to_ulong();
} }
@ -138,9 +131,8 @@ namespace GhettoCipher
} }
//! Will convert a flexible data block to a string //! Will convert a flexible data block to a string
//! //! The difference to BitsToBytes() is, that it strips excess nullbytes //! The difference to BitsToBytes() is, that it strips excess nullbytes
inline std::string BitsToString(const Flexblock& bits) inline std::string BitsToString(const Flexblock& bits) {
{
// Decode to bytes // Decode to bytes
std::string text = BitsToBytes(bits); std::string text = BitsToBytes(bits);
@ -151,51 +143,52 @@ namespace GhettoCipher
} }
//! Turns a fixed-size data block into a hex-string //! Turns a fixed-size data block into a hex-string
inline std::string BitblockToHexstring(const Block& b) inline std::string BitblockToHexstring(const Block& b) {
{
std::stringstream ss; std::stringstream ss;
const std::string charset = "0123456789abcdef"; const std::string charset = "0123456789abcdef";
const std::string bstr = b.to_string(); const std::string bstr = b.to_string();
for (std::size_t i = 0; i < bstr.size(); i += 4) for (std::size_t i = 0; i < bstr.size(); i += 4) {
ss << charset[std::bitset<4>(bstr.substr(i, 4)).to_ulong()]; ss << charset[std::bitset<4>(bstr.substr(i, 4)).to_ulong()];
}
return ss.str(); return ss.str();
} }
//! Turns a flexible data block into a hex-string //! Turns a flexible data block into a hex-string
inline std::string BitsToHexstring(const Flexblock& b) inline std::string BitsToHexstring(const Flexblock& b) {
{
std::stringstream ss; std::stringstream ss;
const std::string charset = "0123456789abcdef"; const std::string charset = "0123456789abcdef";
const std::string bstr = b; const std::string bstr = b;
for (std::size_t i = 0; i < bstr.size(); i += 4) for (std::size_t i = 0; i < bstr.size(); i += 4) {
ss << charset[std::bitset<4>(bstr.substr(i, 4)).to_ulong()]; ss << charset[std::bitset<4>(bstr.substr(i, 4)).to_ulong()];
}
return ss.str(); return ss.str();
} }
//! Turns a hex string into a fixed-size data block //! Turns a hex string into a fixed-size data block
inline Block HexstringToBitblock(const std::string& hexstring) inline Block HexstringToBitblock(const std::string& hexstring) {
{
std::stringstream ss; std::stringstream ss;
for (std::size_t i = 0; i < hexstring.size(); i++) for (std::size_t i = 0; i < hexstring.size(); i++) {
{
const char c = hexstring[i]; const char c = hexstring[i];
// Get value // Get value
std::size_t value; std::size_t value;
if ((c >= '0') && (c <= '9')) if ((c >= '0') && (c <= '9')) {
// Is it a number? // Is it a number?
value = ((std::size_t)c - '0') + 0; value = ((std::size_t)c - '0') + 0;
else if ((c >= 'a') && (c <= 'f')) }
else if ((c >= 'a') && (c <= 'f')) {
// Else, it is a lowercase letter // Else, it is a lowercase letter
value = ((std::size_t)c - 'a') + 10; value = ((std::size_t)c - 'a') + 10;
else }
else {
throw std::logic_error("non-hex string detected in HexstringToBits()"); throw std::logic_error("non-hex string detected in HexstringToBits()");
}
// Append to our bits // Append to our bits
ss << std::bitset<4>(value); ss << std::bitset<4>(value);
@ -205,24 +198,25 @@ namespace GhettoCipher
} }
//! Turns a hex string into a flexible data block //! Turns a hex string into a flexible data block
inline Flexblock HexstringToBits(const std::string& hexstring) inline Flexblock HexstringToBits(const std::string& hexstring) {
{
std::stringstream ss; std::stringstream ss;
for (std::size_t i = 0; i < hexstring.size(); i++) for (std::size_t i = 0; i < hexstring.size(); i++) {
{
const char c = hexstring[i]; const char c = hexstring[i];
// Get value // Get value
std::size_t value; std::size_t value;
if ((c >= '0') && (c <= '9')) if ((c >= '0') && (c <= '9')) {
// Is it a number? // Is it a number?
value = ((std::size_t)c - '0') + 0; value = ((std::size_t)c - '0') + 0;
else if ((c >= 'a') && (c <= 'f')) }
else if ((c >= 'a') && (c <= 'f')) {
// Else, it is a lowercase letter // Else, it is a lowercase letter
value = ((std::size_t)c - 'a') + 10; value = ((std::size_t)c - 'a') + 10;
else }
else {
throw std::logic_error("non-hex string detected in HexstringToBits()"); throw std::logic_error("non-hex string detected in HexstringToBits()");
}
// Append to our bits // Append to our bits
ss << std::bitset<4>(value); ss << std::bitset<4>(value);
@ -235,14 +229,12 @@ namespace GhettoCipher
//! Note that if your password is shorter (in bits) than BLOCK_SIZE, the rest of the key will be padded with 0 (see next line!). //! Note that if your password is shorter (in bits) than BLOCK_SIZE, the rest of the key will be padded with 0 (see next line!).
//! To provide a better initial key, (and to get rid of padding zeroes), the raw result (b) will be xor'd with an initialization vector based on b. //! To provide a better initial key, (and to get rid of padding zeroes), the raw result (b) will be xor'd with an initialization vector based on b.
//! : return b ^ iv(b) //! : return b ^ iv(b)
inline Block PasswordToKey(const std::string& in) inline Block PasswordToKey(const std::string& in) {
{
// Let's provide a nice initial value to be sure even a password of length 0 results in a proper key // Let's provide a nice initial value to be sure even a password of length 0 results in a proper key
Block b = InitializationVector(StringToBitblock("3J7IipfQTDJbO8jtasz9PgWui6faPaEMOuVuAqyhB1S2CRcLw5caawewgDUEG1WN")); Block b = InitializationVector(StringToBitblock("3J7IipfQTDJbO8jtasz9PgWui6faPaEMOuVuAqyhB1S2CRcLw5caawewgDUEG1WN"));
// Segment the password in segments of key-size, and xor them together. // Segment the password in segments of key-size, and xor them together.
for (std::size_t i = 0; i < in.size(); i += BLOCK_SIZE / 8) for (std::size_t i = 0; i < in.size(); i += BLOCK_SIZE / 8) {
{
const Block fragment = StringToBitblock( const Block fragment = StringToBitblock(
PadStringToLength(in.substr(i, BLOCK_SIZE / 8), BLOCK_SIZE / 8, 0, false) PadStringToLength(in.substr(i, BLOCK_SIZE / 8), BLOCK_SIZE / 8, 0, false)
); );
@ -251,22 +243,19 @@ namespace GhettoCipher
// To provide diffusion, hash fragment to fragment' first // To provide diffusion, hash fragment to fragment' first
b ^= Block(Cipher(fragment).Encipher(fragment.to_string())); b ^= Block(Cipher(fragment).Encipher(fragment.to_string()));
} }
return b; return b;
} }
//! Will reduce a flexblock (they are of arbitrary length) to a single block. //! Will reduce a flexblock (they are of arbitrary length) to a single block.
//! This single block should change completely, if a single bit in the input flexblock changes anywhere. //! This single block should change completely, if a single bit in the input flexblock changes anywhere.
inline Block ReductionFunction_Flexblock2Block(const Flexblock& in) inline Block ReductionFunction_Flexblock2Block(const Flexblock& in) {
{
Block b; // No initialization vector needed here Block b; // No initialization vector needed here
// Segment the input in segments of BLOCK_SIZE, and xor them together. // Segment the input in segments of BLOCK_SIZE, and xor them together.
for (std::size_t i = 0; i < in.size(); i += BLOCK_SIZE) for (std::size_t i = 0; i < in.size(); i += BLOCK_SIZE) {
{
const Block fragment = Block(PadStringToLength(in.substr(i, BLOCK_SIZE), BLOCK_SIZE, 0, false)); const Block fragment = Block(PadStringToLength(in.substr(i, BLOCK_SIZE), BLOCK_SIZE, 0, false));
// To provide confusion, xor the blocks together // To provide confusion, xor the blocks together
// To provide diffusion, hash fragment to fragment' first // To provide diffusion, hash fragment to fragment' first
b ^= Block(Cipher(fragment).Encipher(fragment.to_string())); b ^= Block(Cipher(fragment).Encipher(fragment.to_string()));
@ -276,13 +265,13 @@ namespace GhettoCipher
} }
//! Will read a file into a flexblock //! Will read a file into a flexblock
inline Flexblock ReadFileToBits(const std::string& filepath) inline Flexblock ReadFileToBits(const std::string& filepath) {
{
// Read file // Read file
std::ifstream ifs(filepath, std::ios::binary); std::ifstream ifs(filepath, std::ios::binary);
if (!ifs.good()) if (!ifs.good()) {
throw std::runtime_error("Unable to open ifilestream!"); throw std::runtime_error("Unable to open ifilestream!");
}
std::stringstream ss; std::stringstream ss;
std::copy( std::copy(
@ -300,16 +289,16 @@ namespace GhettoCipher
} }
//! Will save bits to a binary file //! Will save bits to a binary file
inline void WriteBitsToFile(const std::string& filepath, const Flexblock& bits) inline void WriteBitsToFile(const std::string& filepath, const Flexblock& bits) {
{
// Convert bits to bytes // Convert bits to bytes
const std::string bytes = BitsToBytes(bits); const std::string bytes = BitsToBytes(bits);
// Write bits to file // Write bits to file
std::ofstream ofs(filepath, std::ios::binary); std::ofstream ofs(filepath, std::ios::binary);
if (!ofs.good()) if (!ofs.good()) {
throw std::runtime_error("Unable to open ofilestream!"); throw std::runtime_error("Unable to open ofilestream!");
}
ofs.write(bytes.data(), bytes.length()); ofs.write(bytes.data(), bytes.length());
ofs.close(); ofs.close();
@ -317,3 +306,4 @@ namespace GhettoCipher
return; return;
} }
} }

View File

@ -1,2 +1,3 @@
#pragma once #pragma once
#define GHETTOCRYPT_VERSION 0.21 #define GHETTOCRYPT_VERSION 0.21

View File

@ -5,114 +5,111 @@
#include "InitializationVector.h" #include "InitializationVector.h"
GhettoCipher::Cipher::Cipher(const Block& key) GhettoCipher::Cipher::Cipher(const Block& key)
: :
key { key }, key { key },
initializationVector(InitializationVector(key)) initializationVector(InitializationVector(key)) {
{
return; return;
} }
GhettoCipher::Cipher::Cipher(const std::string& password) GhettoCipher::Cipher::Cipher(const std::string& password)
: :
key { PasswordToKey(password) }, key { PasswordToKey(password) },
initializationVector(InitializationVector(key)) initializationVector(InitializationVector(key)) {
{ return;
return;
} }
GhettoCipher::Cipher::~Cipher() GhettoCipher::Cipher::~Cipher() {
{ // Clear key memory
// Clear key memory ZeroKeyMemory();
ZeroKeyMemory();
return; return;
} }
void GhettoCipher::Cipher::SetKey(const Block& key) void GhettoCipher::Cipher::SetKey(const Block& key) {
{ ZeroKeyMemory();
ZeroKeyMemory();
this->key = key; this->key = key;
return; return;
} }
void GhettoCipher::Cipher::SetPassword(const std::string& password) void GhettoCipher::Cipher::SetPassword(const std::string& password) {
{ ZeroKeyMemory();
ZeroKeyMemory();
key = PasswordToKey(password); key = PasswordToKey(password);
return; return;
} }
GhettoCipher::Flexblock GhettoCipher::Cipher::Encipher(const Flexblock& data, bool printProgress) const GhettoCipher::Flexblock GhettoCipher::Cipher::Encipher(const Flexblock& data, bool printProgress) const {
{ // Split cleartext into blocks
// Split cleartext into blocks std::vector<Block> blocks;
std::vector<Block> blocks;
for (std::size_t i = 0; i < data.size(); i += BLOCK_SIZE) for (std::size_t i = 0; i < data.size(); i += BLOCK_SIZE) {
blocks.push_back(Block( blocks.push_back(Block(
PadStringToLength(data.substr(i, BLOCK_SIZE), BLOCK_SIZE, '0', false)) PadStringToLength(data.substr(i, BLOCK_SIZE), BLOCK_SIZE, '0', false))
); );
}
// Encrypt individual blocks using cipher block chaining // Encrypt individual blocks using cipher block chaining
Feistel feistel(key); Feistel feistel(key);
for (std::size_t i = 0; i < blocks.size(); i++) 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.
// 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)) {
if ((i % ((blocks.size() > 1000)? 100 : 10) == 0) && (printProgress)) std::cout << "Encrypting... (Block " << i << " / " << blocks.size() << " - " << ((float)i*100 / blocks.size()) << "%)" << std::endl;
std::cout << "Encrypting... (Block " << i << " / " << blocks.size() << " - " << ((float)i*100 / blocks.size()) << "%)" << std::endl; }
const Block& lastBlock = (i>0) ? blocks[i-1] : initializationVector;
blocks[i] = feistel.Encipher(blocks[i] ^ lastBlock); // Xor last cipher block with new clear text block before E()
}
// Concatenate ciphertext blocks back into a flexblock const Block& lastBlock = (i>0) ? blocks[i-1] : initializationVector;
std::stringstream ss; blocks[i] = feistel.Encipher(blocks[i] ^ lastBlock); // Xor last cipher block with new clear text block before E()
for (Block& b : blocks) }
ss << b;
// Return it // Concatenate ciphertext blocks back into a flexblock
return ss.str(); std::stringstream ss;
for (Block& b : blocks) {
ss << b;
}
// Return it
return ss.str();
} }
GhettoCipher::Flexblock GhettoCipher::Cipher::Decipher(const Flexblock& data, bool printProgress) const GhettoCipher::Flexblock GhettoCipher::Cipher::Decipher(const Flexblock& data, bool printProgress) const {
{ // Split ciphertext into blocks
// Split ciphertext into blocks std::vector<Block> blocks;
std::vector<Block> blocks;
for (std::size_t i = 0; i < data.size(); i += BLOCK_SIZE) for (std::size_t i = 0; i < data.size(); i += BLOCK_SIZE) {
blocks.push_back(Block( blocks.push_back(Block(
PadStringToLength(data.substr(i, BLOCK_SIZE), BLOCK_SIZE, '0', false)) PadStringToLength(data.substr(i, BLOCK_SIZE), BLOCK_SIZE, '0', false))
); );
}
// Decrypt individual blocks // Decrypt individual blocks
Feistel feistel(key); Feistel feistel(key);
// We can't do this in-loop for decryption, because we are decrypting the blocks in-place. // We can't do this in-loop for decryption, because we are decrypting the blocks in-place.
Block lastBlock = initializationVector; 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]; 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;
}
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 Block tmpCopy = blocks[i];
lastBlock = std::move(tmpCopy); 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
}
// Concatenate ciphertext blocks back into a flexblock lastBlock = std::move(tmpCopy);
std::stringstream ss; }
for (Block& b : blocks)
ss << b;
// Return it // Concatenate ciphertext blocks back into a flexblock
return ss.str(); std::stringstream ss;
for (Block& b : blocks) {
ss << b;
}
// Return it
return ss.str();
} }
// These pragmas only work for MSVC and g++, as far as i know. Beware!!! // These pragmas only work for MSVC and g++, as far as i know. Beware!!!
@ -122,13 +119,13 @@ GhettoCipher::Flexblock GhettoCipher::Cipher::Decipher(const Flexblock& data, bo
#pragma GCC push_options #pragma GCC push_options
#pragma GCC optimize ("O0") #pragma GCC optimize ("O0")
#endif #endif
void GhettoCipher::Cipher::ZeroKeyMemory() void GhettoCipher::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,51 +3,46 @@
#include "Util.h" #include "Util.h"
#include "Config.h" #include "Config.h"
GhettoCipher::Feistel::Feistel(const Block& key) GhettoCipher::Feistel::Feistel(const Block& key) {
{
SetKey(key); SetKey(key);
return; return;
} }
GhettoCipher::Feistel::~Feistel() GhettoCipher::Feistel::~Feistel() {
{
ZeroKeyMemory(); ZeroKeyMemory();
return; return;
} }
void GhettoCipher::Feistel::SetKey(const Block& key) void GhettoCipher::Feistel::SetKey(const Block& key) {
{
GenerateRoundKeys(key); GenerateRoundKeys(key);
return; return;
} }
GhettoCipher::Block GhettoCipher::Feistel::Encipher(const Block& data) GhettoCipher::Block GhettoCipher::Feistel::Encipher(const Block& data) {
{
return Run(data, false); return Run(data, false);
} }
GhettoCipher::Block GhettoCipher::Feistel::Decipher(const Block& data) GhettoCipher::Block GhettoCipher::Feistel::Decipher(const Block& data) {
{
return Run(data, true); return Run(data, true);
} }
GhettoCipher::Block GhettoCipher::Feistel::Run(const Block& data, bool reverseKeys) GhettoCipher::Block GhettoCipher::Feistel::Run(const Block& data, bool reverseKeys) {
{
const auto splitData = FeistelSplit(data); const auto splitData = FeistelSplit(data);
GhettoCipher::Halfblock l = splitData.first; GhettoCipher::Halfblock l = splitData.first;
GhettoCipher::Halfblock r = splitData.second; GhettoCipher::Halfblock r = splitData.second;
Halfblock tmp; Halfblock tmp;
for (std::size_t i = 0; i < N_ROUNDS; i++) for (std::size_t i = 0; i < N_ROUNDS; i++) {
{
// Calculate key index // Calculate key index
std::size_t keyIndex; std::size_t keyIndex;
if (reverseKeys) if (reverseKeys) {
keyIndex = N_ROUNDS - i - 1; keyIndex = N_ROUNDS - i - 1;
else }
else {
keyIndex = i; keyIndex = i;
}
// Do a feistel round // Do a feistel round
tmp = r; tmp = r;
@ -62,8 +57,7 @@ GhettoCipher::Block GhettoCipher::Feistel::Run(const Block& data, bool reverseKe
return FeistelCombine(r, l); return FeistelCombine(r, l);
} }
GhettoCipher::Halfblock GhettoCipher::Feistel::F(Halfblock m, const Block& key) GhettoCipher::Halfblock GhettoCipher::Feistel::F(Halfblock m, const Block& key) {
{
// Made-up F function // Made-up F function
// Expand to full bitwidth // Expand to full bitwidth
@ -79,8 +73,7 @@ GhettoCipher::Halfblock GhettoCipher::Feistel::F(Halfblock m, const Block& key)
std::stringstream ss; std::stringstream ss;
const std::string m_str = m_expanded.to_string(); const std::string m_str = m_expanded.to_string();
for (std::size_t i = 0; i < BLOCK_SIZE; i += 4) for (std::size_t i = 0; i < BLOCK_SIZE; i += 4) {
{
ss << SBox(m_str.substr(i, 4)); ss << SBox(m_str.substr(i, 4));
} }
@ -90,8 +83,7 @@ GhettoCipher::Halfblock GhettoCipher::Feistel::F(Halfblock m, const Block& key)
return CompressionFunction(m_expanded); return CompressionFunction(m_expanded);
} }
std::pair<GhettoCipher::Halfblock, GhettoCipher::Halfblock> GhettoCipher::Feistel::FeistelSplit(const Block& block) std::pair<GhettoCipher::Halfblock, GhettoCipher::Halfblock> GhettoCipher::Feistel::FeistelSplit(const Block& block) {
{
const std::string bits = block.to_string(); const std::string bits = block.to_string();
Halfblock l(bits.substr(0, bits.size() / 2)); Halfblock l(bits.substr(0, bits.size() / 2));
@ -100,13 +92,11 @@ std::pair<GhettoCipher::Halfblock, GhettoCipher::Halfblock> GhettoCipher::Feiste
return std::make_pair(l, r); return std::make_pair(l, r);
} }
GhettoCipher::Block GhettoCipher::Feistel::FeistelCombine(const Halfblock& l, const Halfblock& r) GhettoCipher::Block GhettoCipher::Feistel::FeistelCombine(const Halfblock& l, const Halfblock& r) {
{
return Block(l.to_string() + r.to_string()); return Block(l.to_string() + r.to_string());
} }
GhettoCipher::Block GhettoCipher::Feistel::ExpansionFunction(const Halfblock& block) GhettoCipher::Block GhettoCipher::Feistel::ExpansionFunction(const Halfblock& block) {
{
std::stringstream ss; std::stringstream ss;
const std::string bits = block.to_string(); const std::string bits = block.to_string();
@ -117,8 +107,7 @@ GhettoCipher::Block GhettoCipher::Feistel::ExpansionFunction(const Halfblock& bl
expansionMap["11"] = "0111"; expansionMap["11"] = "0111";
// We have to double the bits! // We have to double the bits!
for (std::size_t i = 0; i < HALFBLOCK_SIZE; i += 2) for (std::size_t i = 0; i < HALFBLOCK_SIZE; i += 2) {
{
const std::string sub = bits.substr(i, 2); const std::string sub = bits.substr(i, 2);
ss << expansionMap[sub]; ss << expansionMap[sub];
} }
@ -126,8 +115,7 @@ GhettoCipher::Block GhettoCipher::Feistel::ExpansionFunction(const Halfblock& bl
return Block(ss.str()); return Block(ss.str());
} }
GhettoCipher::Halfblock GhettoCipher::Feistel::CompressionFunction(const Block& block) GhettoCipher::Halfblock GhettoCipher::Feistel::CompressionFunction(const Block& block) {
{
std::stringstream ss; std::stringstream ss;
const std::string bits = block.to_string(); const std::string bits = block.to_string();
@ -150,8 +138,7 @@ GhettoCipher::Halfblock GhettoCipher::Feistel::CompressionFunction(const Block&
compressionMap["1111"] = "01"; compressionMap["1111"] = "01";
// We have to half the bits! // We have to half the bits!
for (std::size_t i = 0; i < BLOCK_SIZE; i += 4) for (std::size_t i = 0; i < BLOCK_SIZE; i += 4) {
{
const std::string sub = bits.substr(i, 4); const std::string sub = bits.substr(i, 4);
ss << compressionMap[sub]; ss << compressionMap[sub];
} }
@ -159,12 +146,10 @@ GhettoCipher::Halfblock GhettoCipher::Feistel::CompressionFunction(const Block&
return Halfblock(ss.str()); return Halfblock(ss.str());
} }
std::string GhettoCipher::Feistel::SBox(const std::string& in) std::string GhettoCipher::Feistel::SBox(const std::string& in) {
{
static std::unordered_map<std::string, std::string> subMap; static std::unordered_map<std::string, std::string> subMap;
static bool mapInitialized = false; static bool mapInitialized = false;
if (!mapInitialized) if (!mapInitialized) {
{
subMap["0000"] = "1100"; subMap["0000"] = "1100";
subMap["0001"] = "1000"; subMap["0001"] = "1000";
subMap["0010"] = "0001"; subMap["0010"] = "0001";
@ -187,8 +172,7 @@ std::string GhettoCipher::Feistel::SBox(const std::string& in)
return subMap[in]; return subMap[in];
} }
void GhettoCipher::Feistel::GenerateRoundKeys(const Block& seedKey) void GhettoCipher::Feistel::GenerateRoundKeys(const Block& seedKey) {
{
// Clear initial key memory // Clear initial key memory
ZeroKeyMemory(); ZeroKeyMemory();
roundKeys = Keyset(); roundKeys = Keyset();
@ -205,10 +189,12 @@ void GhettoCipher::Feistel::GenerateRoundKeys(const Block& seedKey)
// if it is a multiple of 4, we'll shift it by 1 into the opposite direction // if it is a multiple of 4, we'll shift it by 1 into the opposite direction
const std::size_t setBits1 = compressedSeed1.count(); const std::size_t setBits1 = compressedSeed1.count();
if (setBits1 % 4 == 0) if (setBits1 % 4 == 0) {
compressedSeed1 = Shiftr(compressedSeed1, 1); compressedSeed1 = Shiftr(compressedSeed1, 1);
else if (setBits1 % 3 == 0) }
else if (setBits1 % 3 == 0) {
compressedSeed1 = Shiftl(compressedSeed1, 1); compressedSeed1 = Shiftl(compressedSeed1, 1);
}
// Now apply substitution // Now apply substitution
std::stringstream ssKey1; std::stringstream ssKey1;
@ -216,8 +202,7 @@ void GhettoCipher::Feistel::GenerateRoundKeys(const Block& seedKey)
const std::string bitsKey1 = compressedSeed1.to_string(); const std::string bitsKey1 = compressedSeed1.to_string();
const std::string bitsKey2 = compressedSeed2.to_string(); const std::string bitsKey2 = compressedSeed2.to_string();
for (std::size_t i = 0; i < HALFBLOCK_SIZE; i += 4) for (std::size_t i = 0; i < HALFBLOCK_SIZE; i += 4) {
{
ssKey1 << SBox(bitsKey1.substr(i, 4)); ssKey1 << SBox(bitsKey1.substr(i, 4));
ssKey2 << SBox(bitsKey2.substr(i, 4)); ssKey2 << SBox(bitsKey2.substr(i, 4));
} }
@ -230,11 +215,9 @@ void GhettoCipher::Feistel::GenerateRoundKeys(const Block& seedKey)
roundKeys[0] = ExpansionFunction(compressedSeed1) ^ seedKey; roundKeys[0] = ExpansionFunction(compressedSeed1) ^ seedKey;
roundKeys[1] = ExpansionFunction(compressedSeed2) ^ seedKey; roundKeys[1] = ExpansionFunction(compressedSeed2) ^ seedKey;
// Now derive all other round keys // Now derive all other round keys
for (std::size_t i = 2; i < roundKeys.size(); i++) for (std::size_t i = 2; i < roundKeys.size(); i++) {
{
// Initialize new round key with last round key // Initialize new round key with last round key
Block newKey = roundKeys[i - 1]; Block newKey = roundKeys[i - 1];
@ -262,10 +245,10 @@ void GhettoCipher::Feistel::GenerateRoundKeys(const Block& seedKey)
#pragma GCC push_options #pragma GCC push_options
#pragma GCC optimize ("O0") #pragma GCC optimize ("O0")
#endif #endif
void GhettoCipher::Feistel::ZeroKeyMemory() void GhettoCipher::Feistel::ZeroKeyMemory() {
{ for (Block& key : roundKeys) {
for (Block& key : roundKeys)
key.reset(); key.reset();
}
return; return;
} }
@ -274,3 +257,4 @@ void GhettoCipher::Feistel::ZeroKeyMemory()
#elif defined __GNUG__ #elif defined __GNUG__
#pragma GCC pop_options #pragma GCC pop_options
#endif #endif

View File

@ -2,90 +2,83 @@
#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) std::string GhettoCipher::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 // Recode the ascii-string to bits
const Flexblock cleartext_bits = StringToBits(cleartext); const Flexblock cleartext_bits = StringToBits(cleartext);
// Encrypt our cleartext bits // Encrypt our cleartext bits
const Flexblock ciphertext_bits = cipher.Encipher(cleartext_bits); const Flexblock ciphertext_bits = cipher.Encipher(cleartext_bits);
// Recode the ciphertext bits to a hex-string // Recode the ciphertext bits to a hex-string
const std::string ciphertext = BitsToHexstring(ciphertext_bits); const std::string ciphertext = BitsToHexstring(ciphertext_bits);
// Return it // Return it
return ciphertext; return ciphertext;
} }
std::string GhettoCipher::GhettoCryptWrapper::DecryptString(const std::string& ciphertext, const std::string& password) std::string GhettoCipher::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 // Recode the hex-string to bits
const Flexblock ciphertext_bits = HexstringToBits(ciphertext); const Flexblock ciphertext_bits = HexstringToBits(ciphertext);
// Decrypt the ciphertext bits // Decrypt the ciphertext bits
const std::string cleartext_bits = cipher.Decipher(ciphertext_bits); const std::string cleartext_bits = cipher.Decipher(ciphertext_bits);
// Recode the cleartext bits to an ascii-string // Recode the cleartext bits to an ascii-string
const std::string cleartext = BitsToString(cleartext_bits); const std::string cleartext = BitsToString(cleartext_bits);
// Return it // Return it
return cleartext; return cleartext;
} }
bool GhettoCipher::GhettoCryptWrapper::EncryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport) bool GhettoCipher::GhettoCryptWrapper::EncryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport) {
{ try {
try // Read the file to bits
{ const Flexblock cleartext_bits = ReadFileToBits(filename_in);
// Read the file to bits
const Flexblock cleartext_bits = ReadFileToBits(filename_in);
// 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);
// 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, printProgressReport);
// Write our ciphertext bits to file // Write our ciphertext bits to file
WriteBitsToFile(filename_out, ciphertext_bits); WriteBitsToFile(filename_out, ciphertext_bits);
return true; return true;
} }
catch (std::runtime_error&) catch (std::runtime_error&) {
{ return false;
return false; }
}
} }
bool GhettoCipher::GhettoCryptWrapper::DecryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport) bool GhettoCipher::GhettoCryptWrapper::DecryptFile(const std::string& filename_in, const std::string& filename_out, const std::string& password, bool printProgressReport) {
{ try {
try // Read the file to bits
{ const Flexblock ciphertext_bits = ReadFileToBits(filename_in);
// Read the file to bits
const Flexblock ciphertext_bits = ReadFileToBits(filename_in);
// 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);
// Decrypt the ciphertext bits // Decrypt the ciphertext bits
const Flexblock cleartext_bits = cipher.Decipher(ciphertext_bits, printProgressReport); const Flexblock cleartext_bits = cipher.Decipher(ciphertext_bits, printProgressReport);
// Write our cleartext bits to file // Write our cleartext bits to file
WriteBitsToFile(filename_out, cleartext_bits); WriteBitsToFile(filename_out, cleartext_bits);
return true; return true;
} }
catch (std::runtime_error&) catch (std::runtime_error&) {
{ return false;
return false; }
}
} }

View File

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