#include <iostream> #include <unistd.h> using namespace std; const string DEFAULT; const int DEFAULT_LEN{2}; const string MD5{"$1$"}; const int MD5_LEN{8}; const string SHA256{"$5$"}; const int SHA256_LEN{16}; const string SHA512{"$6$"}; const int SHA512_LEN{16}; enum class AlgorithmT {DEFAULT, MD5, SHA256, SHA512}; void DoCrypt(string password, AlgorithmT system); void CheckCrypt(string password, AlgorithmT system); string MakeSalt(AlgorithmT system); string MakeSaltString(string prefix, int length); int main() { srand(time(nullptr)); string myWord{"hello"}; DoCrypt(myWord, AlgorithmT::DEFAULT); DoCrypt(myWord, AlgorithmT::DEFAULT); DoCrypt(myWord, AlgorithmT::MD5); DoCrypt(myWord, AlgorithmT::SHA256); DoCrypt(myWord, AlgorithmT::SHA512); CheckCrypt(myWord, AlgorithmT::DEFAULT); CheckCrypt(myWord, AlgorithmT::MD5); return 0; } string MakeSaltString(string prefix, int length){ string rv{prefix}; for(int i = 0; i < length; ++i) { switch(rand() %2) { case 0: rv += rand()%10 + '0'; break; case 1: rv += rand()%26 + 'A'; break; case 2: rv += rand()%26 + 'a'; break; } } if (length > 2) { rv += '$'; } return rv; } string MakeSalt(AlgorithmT method) { string salt; switch(method) { case AlgorithmT::MD5: cout << "Using MD5 Encryption" << endl; salt = MakeSaltString(MD5, MD5_LEN); break; case AlgorithmT::SHA256: cout << "Using SHA256 Encryption" << endl; salt = MakeSaltString(SHA256, SHA256_LEN); break; case AlgorithmT::SHA512: cout << "Using SHA512 Encryption" << endl; salt = MakeSaltString(SHA512, SHA512_LEN); break; case AlgorithmT::DEFAULT: default: cout << "Using Default Encryption" << endl; salt = MakeSaltString(DEFAULT, DEFAULT_LEN); } return salt; } void CheckCrypt(string password, AlgorithmT system) { string salt = MakeSalt(system); string pass1 = crypt(password.c_str(), salt.c_str()); string pass2 = crypt(password.c_str(), pass1.c_str()); cout << "Checking encryption " << endl; cout << "With the salt " << pass1 << endl; cout << "With the stored password " << pass2 << endl; if (pass1 != pass2) { cout << "Fail" << endl; } else { cout << "Success" << endl; } cout << endl << endl; return; } void DoCrypt(string password, AlgorithmT system){ string salt = MakeSalt(system); cout << "The salt is \"" << salt << '"' << endl; cout << "The hash is \"" << crypt(password.c_str(), salt.c_str()) << '"' << endl; cout << endl; }