Qtの基礎 - ハッシュ値
提供: MochiuWiki : SUSE, EC, PCB
概要
Qtにおいて、ハッシュ値を求める手順を記載する。
ハッシュ化
MD5、SHA-2、SHA-3等のハッシュを求める場合、QCryptographicHashクラスのhashメソッドを使用する。
以下の例では、任意の文字列から、MD4、MD5、SHA-2、SHA-3のハッシュを計算している。
サポートされているハッシュの詳細については、Qtの公式ドキュメントを参照すること。
#include <QCoreApplication>
#include <QCryptographicHash>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// ハッシュ化する文字列
QString input = "Hello, world!";
// MD4
QByteArray md4Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Md4);
QString md4HexHash = md4Hash.toHex();
qDebug() << "MD4 Hash:" << md4HexHash;
// MD5
QByteArray md5Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Md5);
QString md5HexHash = md5Hash.toHex();
qDebug() << "MD5 Hash:" << md5HexHash;
// SHA-2 (SHA-224)
QByteArray sha224Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha224);
QString sha224HexHash = sha224Hash.toHex();
qDebug() << "SHA-2 (SHA-224) Hash:" << sha224HexHash;
// SHA-2 (SHA-256)
QByteArray sha256Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha256);
QString sha256HexHash = sha256Hash.toHex();
qDebug() << "SHA-2 (SHA-256) Hash:" << sha256HexHash;
// SHA-2 (SHA-384)
QByteArray sha384Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha384);
QString sha384HexHash = sha384Hash.toHex();
qDebug() << "SHA-2 (SHA-384) Hash:" << sha384HexHash;
// SHA-2 (SHA-512)
QByteArray sha512Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha512);
QString sha512HexHash = sha512Hash.toHex();
qDebug() << "SHA-2 (SHA-512) Hash:" << sha512HexHash;
// SHA-3 (SHA3-224)
QByteArray sha3_224Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha3_224);
QString sha3_224HexHash = sha3_224Hash.toHex();
qDebug() << "SHA-3 (SHA3-224) Hash:" << sha3_224HexHash;
// SHA-3 (SHA3-256)
QByteArray sha3_256Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha3_256);
QString sha3_256HexHash = sha3_256Hash.toHex();
qDebug() << "SHA-3 (SHA3-256) Hash:" << sha3_256HexHash;
// SHA-3 (SHA3-384)
QByteArray sha3_384Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha3_384);
QString sha3_384HexHash = sha3_384Hash.toHex();
qDebug() << "SHA-3 (SHA3-384) Hash:" << sha3_384HexHash;
// SHA-3 (SHA3-512)
QByteArray sha3_512Hash = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha3_512);
QString sha3_512HexHash = sha3_512Hash.toHex();
qDebug() << "SHA-3 (SHA3-512) Hash:" << sha3_512HexHash;
return a.exec();
}