Password Encryption Tool C++
👤 Sharing: AI
```cpp
#include <iostream>
#include <string>
#include <algorithm>
#include <random>
#include <chrono>
#include <iomanip>
#include <sstream>
using namespace std;
// Function to generate a salt
string generateSalt(int length = 16) {
static const string charset =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789!@#$%^&*()_+=-`~[]\{}|;':\",./<>?";
std::mt19937 generator(std::chrono::system_clock::now().time_since_epoch().count());
std::uniform_int_distribution<> distribution(0, charset.length() - 1);
string salt;
for (int i = 0; i < length; ++i) {
salt += charset[distribution(generator)];
}
return salt;
}
// Simple password hashing function (SHA-256-like, but much simplified)
string hashPassword(const string& password, const string& salt) {
string saltedPassword = salt + password;
size_t hash = 5381;
for (char c : saltedPassword) {
hash = ((hash << 5) + hash) + c; // hash * 33 + c
}
stringstream ss;
ss << std::hex << hash;
return ss.str();
}
// Password verification function
bool verifyPassword(const string& password, const string& storedHash, const string& salt) {
string newHash = hashPassword(password, salt);
return (newHash == storedHash);
}
int main() {
string password;
cout << "Enter your password: ";
getline(cin, password); //Use getline to handle passwords with spaces.
// Generate a salt
string salt = generateSalt();
// Hash the password using the salt
string hashedPassword = hashPassword(password, salt);
cout << "\nPassword Encryption Results:" << endl;
cout << "--------------------------" << endl;
cout << "Salt: " << salt << endl;
cout << "Hashed Password: " << hashedPassword << endl;
cout << "--------------------------" << endl;
// Verification example
cout << "\nPassword Verification:" << endl;
string passwordToVerify;
cout << "Enter password to verify: ";
getline(cin, passwordToVerify);
if (verifyPassword(passwordToVerify, hashedPassword, salt)) {
cout << "Password verification successful!" << endl;
} else {
cout << "Password verification failed." << endl;
}
return 0;
}
```
👁️ Viewed: 9
Comments