我编写了下面的程序,该程序应该比较输入的2个密码的SHA512:
#include <iostream>
#include <stdlib.h>
#include <string>
#include "sha512.h"
int main(int argc, char **argv)
{
std::string password;
std::size_t rounds;
std::cout << "Enter your password: ";
std::cin >> password;
std::cout << "You entered '" << password << "'" << std::endl;
std::cout << "\nHow many practice rounds? ";
std::cin >> rounds;
std::string digest = sha512(password.data());
std::fill(begin(password), end(password), '\0'); // Clean memory
std::size_t i;
std::string password2;
std::string digest2;
while(rounds > 0)
{
std::cout << "Enter password: ";
std::cin >> password2;
std::cout << "You entered '" << password2 << "'" << std::endl;
digest2 = sha512(password.data());
std::cout << "Digest 1: " << digest << std::endl;
std::cout << "Digest 2: " << digest2 << std::endl;
std::fill(begin(password2), end(password2), '\0'); // Clean memory
if(digest2 == digest)
{
std::cout << "Password correct, you have " << rounds << " rounds to go" << std::endl;
rounds--;
}
else
{
std::cout << "Password entered incorrectly. This round doesn't count!";
}
}
std::cout << "All done. Have a nice day!";
return EXIT_SUCCESS;
}
问题在于,即使密码相同,SHA512也不匹配。我检查了GDB中的密码文本,并将两个字符串对象作为图像附加在此处。请注意,然后我更改了代码以将string.data()
传递给SHA512算法,因为我担心散列会散列整个字符串对象,并且由于将始终存在单独的字符串对象,因此永远不会匹配。但是,这似乎不是问题。请注意,在屏幕截图中,尽管_M_p值是相同的确切文本,但仍会解析为两个单独的十六进制值。这些可能是指针,但是散列仍然不匹配,因此我不确定这里出了什么问题。
请注意,我现在正在使用http://www.zedwood.com/article/cpp-sha512-function。
程序输出:
Enter your password: test
You entered 'test'
How many practice rounds? 5
Enter password: test
You entered 'test'
Digest 1: ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff
Digest 2: cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e
注意:摘要1是正确的。摘要#2经过第三方哈希程序的验证是不正确的。。但是在程序的终端输出中,看到两个密码是相同的...还记得我只用.data()
来解决此问题,发生了以及普通的旧字符串对象。