使用openssl庫實現(Qt自帶QCryptographicHash)
#include "openssl/sha.h"
enum OPENSSL_TYPE{MD5,SHA1,SHA224,SHA256,SHA384,SHA512}; QByteArray hash(const QByteArray &data, OPENSSL_TYPE type) { int len = 0; unsigned char *result = nullptr; switch (type) { case OPENSSL_TYPE::MD5: { result = new unsigned char[MD5_DIGEST_LENGTH]; len = MD5_DIGEST_LENGTH; #if 1 ::MD5(reinterpret_cast<const uchar *>(data.constData()), static_cast<size_t>( data.length() ), result); #else //適用於文件 MD5_CTX md5_ctx; MD5_Init(&md5_ctx);
MD5_Update(&md5_ctx,
reinterpret_cast<const uchar *>(data.constData()),
static_cast<size_t>( data.length() ) );
MD5_Final(result, &md5_ctx);
#endif
break;
}
case OPENSSL_TYPE::SHA1: {
result = new unsigned char[SHA_DIGEST_LENGTH];
len = SHA_DIGEST_LENGTH;
::SHA1(reinterpret_cast<const uchar *>(data.constData()),
static_cast<size_t>( data.length() ),
result);
break;
}
case OPENSSL_TYPE::SHA224: {
result = new unsigned char[SHA224_DIGEST_LENGTH];
len = SHA224_DIGEST_LENGTH;
::SHA224(reinterpret_cast<const uchar *>(data.constData()),
static_cast<size_t>( data.length() ),
result);
break;
}
case OPENSSL_TYPE::SHA256: {
result = new unsigned char[SHA256_DIGEST_LENGTH];
len = SHA256_DIGEST_LENGTH;
::SHA256(reinterpret_cast<const uchar *>(data.constData()),
static_cast<size_t>( data.length() ),
result);
break;
}
case OPENSSL_TYPE::SHA384: {
result = new unsigned char[SHA384_DIGEST_LENGTH];
len= SHA384_DIGEST_LENGTH;
::SHA384(reinterpret_cast<const uchar *>(data.constData()),
static_cast<size_t>( data.length() ),
result);
break;
}
case OPENSSL_TYPE::SHA512: {
result = new unsigned char[SHA512_DIGEST_LENGTH];
len = SHA512_DIGEST_LENGTH;
::SHA512(reinterpret_cast<const uchar *>(data.constData()),
static_cast<size_t>( data.length() ),
result);
break;
}
}
QByteArray array;
if(result != nullptr)
{
array.append(reinterpret_cast<const char *>(result), len);
delete [] result;
result = nullptr;
}
return array;
}