Qt 5.1 に HMAC 対応が入っていたのでメモ
Qt の開発メーリングリストで今年のはじめに Playground: Crypto module という議論があったのですが、それを見逃していたのでメモ。
Qt 5 対応の QCA 的なライブラリが欲しくて色々探していたら、Qt 5.1 から HMAC のサポートが QtCore に入る ということがわかりました。
新たに QMessageAuthenticationCode というクラスが追加され、以下のように簡単に HMAC-SHA1(等) が計算できるようになります。
QByteArray key = "key"; QByteArray message = "The quick brown fox jumps over the lazy dog"; ... QMessageAuthenticationCode code(QCryptographicHash::Sha1); code.setKey(key); code.addData(message); code.result().toHex(); // returns "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"
簡易的に以下のように書くことも可能です。
QMessageAuthenticationCode::hash(message, key, QCryptographicHash::Sha1).toHex();
今までは以下のようなコードをそれぞれのプロジェクトで書かなければいけなかったのですが、また一つ便利になりましたね。
#include <QCryptographicHash>
static const int BLOCK_SIZE = 64;
QByteArray hmac_sha1(const QByteArray& in_key, const QByteArray& text)
{
QByteArray key(in_key);
if (key.length() > BLOCK_SIZE) {
key = QCryptographicHash::hash(key, QCryptographicHash::Sha1);
}
if (key.length() < BLOCK_SIZE) {
key += QByteArray(BLOCK_SIZE-key.length(), 0);
}
QByteArray o_key_pad(BLOCK_SIZE, char(0x5c));
QByteArray i_key_pad(BLOCK_SIZE, char(0x36));
for (int i=0; i<BLOCK_SIZE; ++i) {
o_key_pad[i] = o_key_pad[i] ^ key.at(i);
i_key_pad[i] = i_key_pad[i] ^ key.at(i);
}
QByteArray ret = QCryptographicHash::hash(i_key_pad + text, QCryptographicHash::Sha1);
ret = QCryptographicHash::hash(o_key_pad + ret, QCryptographicHash::Sha1);
return ret;
}
※ 第6回関東Qt勉強会 の「QtNetwork 入門」という発表の、Qt で OAuth を使う方法 で紹介されているコードの引用です。