cs251/Project3/brute.cpp
2018-10-15 17:24:29 -04:00

103 lines
2.8 KiB
C++

#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include "key.hpp"
#include "brute.hpp"
std::string me;
std::string encrypted;
std::string table_filename;
bool verbose = false;
#define ALPHABET_LENGTH 32
const char alphabet[ALPHABET_LENGTH] = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5'
};
Brute::Brute(const std::string& filename) {
T.resize(N);
std::string buffer;
std::fstream input(filename.c_str(), std::ios::in);
for (int i = 0; i < N; i++) {
std::getline(input, buffer);
T[i].set_string(buffer);
}
input.close();
}
void Brute::decrypt(const std::string& encrypted){
// your code here
Key enc(encrypted);
size_t length = encrypted.length();
char zeroChars[length];
char fullChars[length];
for (int i = 0; i < length; i++) {
zeroChars[i] = alphabet[0]; // Fill with a's.
}
for (int i = 0; i < length; i++) {
fullChars[i] = alphabet[ALPHABET_LENGTH - 1]; // Fill with a's.
}
std::string zeroStr(zeroChars);
std::string fullStr(fullChars);
zeroChars[length - 1] = 'b'; // Set the rightmost char to b to equate the string to 1.
std::string incStr(zeroChars);
Key base(zeroStr);
Key end(fullStr);
Key inc(incStr);
Key search = base; // Copy the base (all zero's).
while (!(search == end)) {
if (search.subset_sum(T, false) == enc) {
search.show_string();
}
search += inc;
}
}
void usage(const std::string& error_msg="") {
if (!error_msg.empty()) std::cout << "ERROR: " << error_msg << '\n';
std::cout << me << ": Brute force cracking of Subset-sum password with "
<< B << " bits precision\n"
<< "USAGE: " << me << " <encrypted> <table file> [options]\n"
<< "\nArguments:\n"
<< " <encrypted>: encrypted password to crack\n"
<< " <table file>: name of file containing the table to use\n"
<< "\nOptions:\n"
<< " -h|--help: print this message\n"
<< " -v|--verbose: select verbose mode\n\n";
exit(0);
}
void initialize(int argc, char* argv[]) {
me = argv[0];
if (argc < 3) usage("Missing arguments");
encrypted = argv[1];
table_filename = argv[2];
for (int i=3; i<argc; ++i) {
std::string arg = argv[i];
if (arg == "-h" || arg == "--help") usage();
else if (arg == "-v" || arg == "--verbose") verbose = true;
else usage("Unrecognized argument: " + arg);
}
}
int main(int argc, char *argv[]){
initialize(argc, argv);
// your code here
Brute brute(table_filename);
brute.decrypt(encrypted);
return 0;
}