#include "stdafx.h"
#include "Hash.h"

#include <QCryptographicHash.h>
#include <QObject>

#include <sstream>
#include <iomanip>

using namespace std;



namespace qut
{


QString Hash::ToMD4(const QString& src)
{
	QCryptographicHash hs(QCryptographicHash::Md4);
	QString s;
	ToHash(hs, src, s);
	return s;
}

QString Hash::ToMD5(const QString& src)
{
	QCryptographicHash hs(QCryptographicHash::Md5);
	QString s;
	ToHash(hs, src, s);
	return s;
}

QString Hash::ToSha1(const QString& src)
{
	QCryptographicHash hs(QCryptographicHash::Sha1);
	QString s;
	ToHash(hs, src, s);
	return s;
}

void Hash::ToHash(QCryptographicHash& hs, const QString& src, QString& dst)
{
	hs.addData(src.toLocal8Bit(), src.length());
	dst = HashToString(hs);
}

QString Hash::HashToString(const QCryptographicHash& hs)
{
	ostringstream s;
	QByteArray h = hs.result();
	for(int i = 0; i < h.length(); ++i)
	{
		const int c = (int)(unsigned char)h.data()[i];
		s << setw(2) << setfill('0') << hex << c;
	}

	return QObject::tr(s.str().c_str());
}


}
