Openssl実現hashアルゴリズム

2446 ワード

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(data.constData()),
              static_cast( data.length() ),
              result);
#else
        //     
        MD5_CTX md5_ctx;
        MD5_Init(&md5_ctx);

        MD5_Update(&md5_ctx,                    reinterpret_cast(data.constData()),                    static_cast( 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(data.constData()),                static_cast( data.length() ),                result);         break;     }     case OPENSSL_TYPE::SHA224: {         result = new unsigned char[SHA224_DIGEST_LENGTH];         len = SHA224_DIGEST_LENGTH;        ::SHA224(reinterpret_cast(data.constData()),                  static_cast( data.length() ),                  result);         break;     }     case OPENSSL_TYPE::SHA256: {         result = new unsigned char[SHA256_DIGEST_LENGTH];         len = SHA256_DIGEST_LENGTH;        ::SHA256(reinterpret_cast(data.constData()),                  static_cast( data.length() ),                  result);         break;     }     case OPENSSL_TYPE::SHA384: {         result = new unsigned char[SHA384_DIGEST_LENGTH];         len= SHA384_DIGEST_LENGTH;        ::SHA384(reinterpret_cast(data.constData()),                  static_cast( data.length() ),                  result);         break;     }     case OPENSSL_TYPE::SHA512: {         result = new unsigned char[SHA512_DIGEST_LENGTH];         len = SHA512_DIGEST_LENGTH;        ::SHA512(reinterpret_cast(data.constData()),                  static_cast( data.length() ),                  result);         break;     }     }     QByteArray array;     if(result != nullptr)     {         array.append(reinterpret_cast(result), len);         delete [] result;         result = nullptr;     }     return array; }