Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Qt5哈希函数在Windows 7和Windows 10上不返回相同的哈希_C++ - Fatal编程技术网

C++ Qt5哈希函数在Windows 7和Windows 10上不返回相同的哈希

C++ Qt5哈希函数在Windows 7和Windows 10上不返回相同的哈希,c++,C++,我想散列一个给定的字符串,然后跨多个平台和操作系统验证散列代码。我刚刚在Qt5.12中实现了这个简单的函数。我使用Windows1064位作为开发机器 void hashCheckFunction(QString input) { QByteArray ba; const char *str = input.toStdString().c_str(); ba.append(str); QByteArray md5Ba=QCryptographicHash:

我想散列一个给定的字符串,然后跨多个平台和操作系统验证散列代码。我刚刚在Qt5.12中实现了这个简单的函数。我使用Windows1064位作为开发机器

void hashCheckFunction(QString input)
{

    QByteArray ba;
    const char *str =   input.toStdString().c_str();
    ba.append(str);

    QByteArray md5Ba=QCryptographicHash::hash(ba,QCryptographicHash::Md5).toHex();
    QString md5hash(md5Ba);
    qDebug()<<"MD5 : "<<md5hash;

    QByteArray shaBa=QCryptographicHash::hash(ba,QCryptographicHash::Sha256).toHex();
    QString sha256hash(shaBa);
    qDebug()<<"SHA 256 : "<<sha256hash;
}
在Windows 7上的输出:

MD5:7fc56270e7a70fa81a5935b72eacbe29

SHA256:559EAD08264D5795D3909718CDD05ABD49572E84FE55590EEF31A88A08FDFFD

在Windows 10上的输出:

MD5:4eb30b25e43174eabe0e13426716ef40

SHA256:a5e37a6bfb24ca261cfa91ed5fb73a89a652164c43cd4f7a99147d18d4508eaf

注意:

  • Windows 10上的输出是正确的,因为Windows 10的输出与 我的PHP脚本生成在Linux服务器上运行的脚本。我有 已验证Windows 10生成的哈希与Linux上的PHP相同 服务器。我这样做只是为了检查哪一个是正确的
  • 对于许多字符串输入,Windows 7和Windows 10上的输出也是相同的。这个 上面的字符串示例是同一函数 生成不同的哈希代码
  • 问题: 为什么我不能在Windows7机器上获得与Windows10类似的哈希值?解决方案是什么?

    input.toStdString()
    构造一个临时的
    std::string
    ,该临时的
    std::string
    只保证在它所处的语句期间有效。 然后使用
    .c_str()
    获取该临时变量的地址,并将其传递给
    ba.append()

    在这两个事件之间,临时字符串被释放,刚刚释放的内存可能发生任何事情。如果它在Windows7上运行,那完全是偶然的

    更具结构性的解决方案是直接按照以下方式构造
    QByteArray

    QByteArray ba = input.toUtf8();
    

    这仍将创建一个临时对象,但
    QByteArray
    赋值运算符将确保内存被复制到
    ba
    (或移动,具体取决于您的Qt版本)。

    您检查过字节数组是否包含相同的数据吗?请在函数中打印出
    输入字符串的内容。如何调用
    hashCheckFunction()
    函数?
    input.toStdString().c_str()
    只在临时
    std::string
    存在时才有效。之后的操作取决于该字符串是否存在,这是一种未定义的行为。使用
    input.toUtf8()
    直接获取
    QByteArray
    。为什么不直接执行
    ba.append(输入)?@Botje:请不要将答案作为评论发布;这个问题现在似乎没有得到正确的回答。
    
    QByteArray ba = input.toUtf8();