C++密码管理器登录逻辑异常:正确密码与密钥验证失败求助
登录验证失败问题排查与修复方案
一、文件读取逻辑冗余且存在风险
你的代码中对密码文件执行了重复读取操作,完全没必要:
std::getline(file, pass); file.open(filePath); file.clear(); file.seekg(0, std::ios::beg); std::getline(file, pass);
第一次getline已经读取了文件第一行内容到pass,后续操作属于重复且无意义的步骤,还可能在文件状态异常时引发未知问题。建议简化为只读模式打开文件,并检查读取是否成功:
std::ifstream file(filePath); // 用ifstream适配只读场景更安全 std::string pass; if (!file.is_open()) { std::cout << "无法打开文件 (Nie można otworzyć pliku)" << std::endl; return false; } if (!std::getline(file, pass)) { // 明确检查读取操作是否成功 std::cout << "读取文件内容失败" << std::endl; return false; }
二、用户输入读取的致命缺陷
使用std::cin >> userPassword读取密码时,会自动截断空格、制表符等空白字符。如果你的原始密码包含空格,用户输入完整带空格的密码后,userPassword只会保留第一个空格前的内容,直接导致与解密后的密码不匹配。
解决方法:改用std::getline读取完整输入,同时处理cin残留的换行符:
std::cout << "Password (Hasło): " << std::endl; std::cin.ignore(); // 忽略之前输入操作留下的换行符 std::getline(std::cin, userPassword); std::cout << "Key (Klucz): " << std::endl; std::cin.ignore(); std::getline(std::cin, key);
三、XOR加解密一致性验证(核心排查点)
这是最可能导致验证失败的原因,必须确认cipher::decrypt与加密逻辑完全匹配:
- 密钥循环规则:XOR加密通常会循环使用密钥(密码长度大于密钥时重复密钥),需确保加密和解密时的循环逻辑完全一致。
- 字符编码与末尾处理:检查加密后的密码写入文件时,是否额外添加了换行符;读取时
getline会自动去掉换行,若加密时包含换行,解密后就会与原始密码出现差异。 - 环境兼容性:ARM64架构下的字符处理是否存在差异?比如是否错误处理了多字节字符。
建议先编写独立测试代码验证加解密逻辑:
#include <iostream> #include "Szyfrowanie.h" int main() { std::string testPass = "TestPasswordWithSpace 123"; std::string testKey = "MySecretKey"; std::string encrypted = cipher::encrypt(testPass, testKey); std::string decrypted = cipher::decrypt(encrypted, testKey); std::cout << "原始密码:" << testPass << std::endl; std::cout << "解密结果:" << decrypted << std::endl; std::cout << "是否匹配:" << (testPass == decrypted ? "是" : "否") << std::endl; return 0; }
四、辅助排查手段
如果以上步骤仍未解决问题,可通过打印细节定位差异:
// 对比用户输入与解密后密码的长度和字符ASCII码 std::cout << "用户输入长度:" << userPassword.size() << std::endl; std::cout << "解密后长度:" << globalPass.size() << std::endl; std::cout << "用户输入字符ASCII:"; for (char c : userPassword) std::cout << (int)c << " "; std::cout << std::endl; std::cout << "解密后字符ASCII:"; for (char c : globalPass) std::cout << (int)c << " "; std::cout << std::endl;
内容的提问来源于stack exchange,提问作者Maja
相关产品推荐
相关产品推荐

