密码管理器密码长度持续增长及重复生成密码的问题求助
Hey, let's tackle your two issues one by one:
1. Fixing the ever-growing password output length
Looking at your code, the problem here is that you keep appending new passwords to the random_keys vector without clearing it between loops. Every time you call reverse.join(random_keys, "--"), you're outputting all passwords generated since the program started, which is why the length keeps increasing.
The fix is straightforward: clear the vector at the start of each loop so you only output the 4 new passwords generated that cycle:
int main() { std::string t = reverse.ascii_lowercase() + reverse.ascii_uppercase() + reverse.digits() + reverse.punctuation(); std::vector<std::string> random_keys; while (true) { std::this_thread::sleep_for(std::chrono::seconds(3)); std::cout << "1s" << std::endl; // Clear the vector to discard old passwords before adding new ones random_keys.clear(); for (int i = 0; i < 4; i++) { random_keys.push_back(reverse.randomString(15, t)); } // Add a newline here to make each cycle's output easier to read std::cout << reverse.join(random_keys, "--") << std::endl; } std::cin.get(); return 0; }
2. Fixing identical passwords every 3 seconds
Your setSeed method uses a static bool set flag, which means it only calls srand(time(NULL)) once during the entire program run. If your randomString function relies on rand(), this should produce sequential random values—but you're seeing identical passwords, which suggests one of two common pitfalls:
- Either your
randomStringfunction is incorrectly resetting the random state somewhere in its implementation - Or you're accidentally re-seeding in a way that locks the random sequence
The cleanest fix is to initialize the seed once at program startup (not every time you generate a password) to ensure the random state progresses correctly. Move the setSeed() call to the very start of main():
int main() { // Initialize the seed ONCE when the program starts reverse.setSeed(); std::string t = reverse.ascii_lowercase() + reverse.ascii_uppercase() + reverse.digits() + reverse.punctuation(); std::vector<std::string> random_keys; while (true) { std::this_thread::sleep_for(std::chrono::seconds(3)); std::cout << "1s" << std::endl; random_keys.clear(); for (int i = 0; i < 4; i++) { random_keys.push_back(reverse.randomString(15, t)); } std::cout << reverse.join(random_keys, "--") << std::endl; } std::cin.get(); return 0; }
A quick side note: since this is a password manager, rand() isn't the most secure choice for randomness. For better security, consider using C++'s modern <random> library—something like std::mt19937 paired with std::random_device for proper entropy.
内容的提问来源于stack exchange,提问作者zrim

