Refactor computing hashes.

For now, this is only used in FileName, because it does not change the semantics of DocFileName::mangledFileName.
This commit is contained in:
Thibaut Cuvelier 2021-10-19 02:24:22 +02:00
parent 40ee8d2a1a
commit 789a537182
3 changed files with 29 additions and 13 deletions

View File

@ -22,7 +22,6 @@
#include "support/Package.h"
#include "support/qstring_helpers.h"
#include <QCryptographicHash>
#include <QDateTime>
#include <QDir>
#include <QFile>
@ -974,17 +973,8 @@ string DocFileName::mangledFileName(string const & dir, bool use_counter, bool e
// Now the real work. Remove the extension.
string mname = support::changeExtension(name, string());
if (encrypt_path) {
QString qname = toqstr(mname);
#if QT_VERSION >= 0x050000
QByteArray hash = QCryptographicHash::hash(qname.toLocal8Bit(),QCryptographicHash::Sha256);
#else
QByteArray hash = QCryptographicHash::hash(qname.toLocal8Bit(),QCryptographicHash::Sha1);
#endif
hash = hash.toHex();
mname = fromqstr(QString(hash));
mname = "export_" + onlyFileName() + "_" + mname;
}
if (encrypt_path)
mname = "export_" + onlyFileName() + "_" + toHexHash(mname);
// The mangled name must be a valid LaTeX name.
// The list of characters to keep is probably over-restrictive,

View File

@ -62,6 +62,8 @@
#include <sstream>
#include <vector>
#include <QCryptographicHash>
#if defined (_WIN32)
#include <io.h>
#include <windows.h>
@ -1309,5 +1311,19 @@ void fileUnlock(int fd, const char * /* lock_file*/)
#endif
}
} //namespace support
std::string toHexHash(const std::string & str)
{
// Use the best available hashing algorithm. Qt 5 proposes SHA-2, but Qt 4 is limited to SHA-1.
#if QT_VERSION >= 0x050000
auto hashAlgo = QCryptographicHash::Sha256;
#else
auto hashAlgo = QCryptographicHash::Sha1;
#endif
QByteArray hash = QCryptographicHash::hash(toqstr(str).toLocal8Bit(), hashAlgo);
return fromqstr(QString(hash.toHex()));
}
} // namespace support
} // namespace lyx

View File

@ -344,6 +344,16 @@ cmd_ret const runCommand(std::string const & cmd);
int fileLock(const char * lock_file);
void fileUnlock(int fd, const char * lock_file);
/** Return the hex-encoded cryptographic hash of a string.
* The hash algorithm is not fixed, but it is determined at compile time.
* This function is typically used to create relatively stable file names,
* because cryptographic hash functions ensure that very small changes in the
* input result in large changes in the output.
* There is no limit in the length of the input string: it can be a file name
* or the contents of a file, for instance.
*/
std::string toHexHash(const std::string & str);
} // namespace support
} // namespace lyx