FuzzyHashing
提供:やる気向上作戦
目次 |
何ですかこれは?
Context Triggered Piecewise Hashing (CTPH)を、C++で実装したものです。
メッセージAおよびBが与えられた場合、通常のハッシュアルゴリズム(MD5、SHA1等)では、AとBが似通っていたとしても、これらに対して生成されるハッシュ値は大きく異なったものになります。しかしながら、CTPHでは、AとBが似通っていた場合、生成されるハッシュ値も似通ったものになります。この面白い性質により、スパムの検出、フォレンジクス、類似文書の探索などへの応用が期待されています。
本コードは、基本的に論文の疑似コードを参考に書き下ろしていますが、論文から具体的な値を読み取れない定数については、ssdeepから拝借しています。
必要環境
Visual Studio 2005およびg++ 4.2.3にて動作を確認。
ダウンロード
ライセンス
Public Domain
例
#include "fuzzyhashing.hpp"
#include <iostream>
#include <fstream>
using namespace fuzzyhashing;
void hashFile(const char* filename)
{
FuzzyHasher hasher;
UInt64 totalSize;
UInt32 suggestedBlockSize = 0;
std::ifstream fin(filename, std::ios::in | std::ios::binary);
char buf[4096];
if (!fin.is_open()) {
std::cerr << "Can't open " << filename << std::endl;
return;
}
fin.seekg(0, std::ios::end);
totalSize = fin.tellg();
fin.seekg(0, std::ios::beg);
hasher.init(totalSize);
while (true) {
while (!fin.eof()) {
fin.read(buf, sizeof(buf));
size_t nread = fin.gcount();
hasher.update((const UInt8*)buf, nread);
}
if (hasher.final(suggestedBlockSize)) {
break;
} else {
hasher.reset(suggestedBlockSize);
fin.clear();
fin.seekg(0, std::ios::beg);
}
}
std::cout << "Triggered count : " << hasher.triggeredCount1() << std::endl;
std::cout << hasher.blockSize()
<< ":" << hasher.signature1()
<< ":" << hasher.signature2()
<< std::endl;
}
int main(int argc, char* argv[])
{
if (argc > 1) {
hashFile(argv[1]);
} else {
std::cerr << "USAGE: fuzzyhashing.exe file" << std::endl;
}
return 0;
}