当表示为 QString 时,MD5 摘要被截断

MD5 digest is truncated when represented as QString

我正在 Windows 8 64 位 OS 上开发 Qt 应用程序。我遇到过这种奇怪的情况,其中 MD5 消息摘要只有 4 个字符长(=32 位)。除了这个异常输入,我得到 16 个字符(=128 位)消息摘要字符串。

MD5 message digest should be fixed length

MD5- Wikipedia

我的代码片段

qDebug()<<"Case 1:=> ";

message1="HYQPTPORKTWKJSVIVXHS1.130hello world!";
input.append(message1);
output=QCryptographicHash::hash(input,QCryptographicHash::Md5);
QString digest1(QString(output).toAscii());
qDebug()<<"md5  string: "<<digest1;
qDebug()<<"length :"<<digest1.length();

qDebug()<<"Case 2:=>";
input=""; // clears previous input
message2="HYQPTPORKTWKJSVIVXHS1.131hello world!";  // put anything else than message1
input.append(message2);
output=QCryptographicHash::hash(input,QCryptographicHash::Md5);
QString digest2(QString(output).toAscii());
qDebug()<<"md5  string: "<<digest2;
qDebug()<<"length :"<<digest2.length();

输出

 Case 1:=>  
md5  string:  ")QÄ" 
length : 4 // here I'm expecting 16
Case 2:=> 
md5  string:  "X,öéö< Ú4Îu" 
length : 16 

我是不是做错了什么?

您正在将 128 位 二进制 MD5 解释为 ASCII。如果您有一个值为“0”的字节(八位),在 C++ 的 ASCII 中,它被认为是 "end of string" 标记。

您需要在 ASCII 中将 MD5 表示为十六进制,而不是尝试按原样在 ASCII 中读取它。

我不会做 Qt,但快速搜索说这样的东西可以做你想做的事:

QString digest2(output.toHex()));

你应该始终确保(尤其是在处理像 C++ 这样的语言时)你完全了解引擎盖下实际发生的事情,在这种特殊情况下,你所有操作的实际底层数据类型是什么.一切都只是内存中的字节,而 C++ 使您能够 "read" 随心所欲地使用这些字节 - 即使它尚未准备好或未准备好。