【发布时间】:2020-11-01 19:16:15
【问题描述】:
我想以与git hash-object 相同的方式散列文件,因此我可以将其与现有散列进行比较,但使用 Qt 和 C++。
this question 的答案显示了如何获得相同的哈希值,但没有一个示例使用 C++。
到目前为止,这是我们尝试过的:
QString fileName = entry.toObject().value( "name" ).toString();
QByteArray shaJson = entry.toObject().value( "sha" ).toString().toUtf8();
QByteArray shaFile;
QFile f( QString( "%1/%2" ).arg( QCoreApplication::applicationDirPath() ).arg( fileName ) );
if( f.open(QFile::ReadOnly ) )
{
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData( QString( "blob " ).toUtf8() ); // start with the string "blob "
hash.addData( QString( "%1" ).arg( f.size() ).toUtf8() ); // add size in bytes of the content
hash.addData( QString( "\0" ).toUtf8() ); // null byte
hash.addData( f.readAll() ); // actual file content
shaFile = hash.result().toHex();
if( shaFile != shaJson ){
}
}
如何用 Qt 实现这种散列方法?
编辑:
这是一个示例哈希输出:
ccbf4f0a52fd5ac59e18448ebadf2ef37c62f54f
使用此文件中的git hash-object 计算:
https://raw.githubusercontent.com/ilia3101/MLV-App/master/pixel_maps/80000301_1808x1007.fpm
这就是我们也喜欢用 Qt 计算的哈希值。
【问题讨论】:
-
您可以发布您尝试过的文件示例吗?链接问题中的空文件和 foobar 示例将是不错的选择。另外,
QString::toUtf8是否包含终止空字符?如果是这样,它会改变哈希结果,因为输入会不同。 -
谢谢!使用
QCryptographicHash计算哈希是可行的。所以这不是如何做sha1哈希的问题。困难的部分是以 git 在散列时相同的方式组合所有部分......我添加了一个示例文件和所需的散列。