openssl 实现hash算法

使用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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值