cryptSpeed.cpp

URL: http://147.64.242.52/~bennett/class/cmac2000/spring2026/notes/two/code/cryptSpeed.cpp
 
#include <iostream>
#include <chrono>
#include <crypt.h>
#include <unistd.h>

using namespace std;

const int LIMIT{1'000'000};

string RandomString(int length);

int main() {
  
      srand(time(nullptr));

      auto start = chrono::high_resolution_clock::now();
     
      string password {"bob"};
      string crypted {crypt(password.c_str(), password.c_str())};

      cout << endl;
      cout << " The encryption of " << password << " is " << crypted << endl;
      cout << endl << endl;
      
      for(int i =0; i < LIMIT; ++i) {
         
         string guessWord = RandomString(rand() %10 + 3);
         string newCrypted {crypt(guessWord.c_str(), guessWord.c_str())};
         if (newCrypted == crypted) {
            cout << "Success" << endl;
         }
      }

      auto end = chrono::high_resolution_clock::now();
      chrono::duration<double> duration = end - start;
      double seconds {duration.count()};

      cout << "Passwords tried " << LIMIT << endl;
      cout << "Execution time: "  << seconds << " seconds" << endl;
      cout << endl << endl;

      cout << "That is " << static_cast<double>( LIMIT) / seconds 
           << " passwords per second." << endl;

      return 0;
}

string RandomString(int length){
   string rv;
   for(int i = 0; i < length; ++i) {
      switch(rand() %3) {
         case 0: rv += rand()%10 + '0'; break;
         case 1: rv += rand()%26 + 'A'; break;
         case 2: rv += rand()%26 + 'a'; break;
      }
   }

   return rv;
}