把嘎嘎 2023-07-24 17:37 采纳率: 41.9%
浏览 25
已结题

c++代码实现QCryptographicHash::hash

有一段qt代码:

QByteArray ba;
ba = QCryptographicHash::hash(ba, QCryptographicHash::Md5);
QString ret = ba.toHex().toUpper();

现要用c++实现这段代码,
给定std::string ba;得到std::string ret

需要怎么实现

  • 写回答

3条回答 默认 最新

  • Leodong. 2023-07-24 18:09
    关注

    该回答通过自己思路及引用到GPTᴼᴾᴱᴺᴬᴵ搜索,得到内容具体如下:
    以下是用C++实现QCryptographicHash::hash的示例代码:

    #include <openssl/md5.h>
    #include <cstring>
    #include <string>
    #include <sstream>
    #include <iomanip>
    
    std::string QCryptographicHash(const std::string& input, const QCryptographicHash::Algorithm algorithm)
    {
        std::string result;
        unsigned char hash[MD5_DIGEST_LENGTH];
        memset(hash, 0, sizeof(hash));
    
        switch (algorithm) {
            case QCryptographicHash::Md5:
                MD5(reinterpret_cast<const unsigned char*>(input.c_str()), input.size(), hash);
                result.resize(MD5_DIGEST_LENGTH);
                memcpy(&result[0], hash, MD5_DIGEST_LENGTH);
                break;
            case QCryptographicHash::Sha1:
                // TODO: Implement SHA1 hash
                break;
            case QCryptographicHash::Sha256:
                // TODO: Implement SHA256 hash
                break;
            case QCryptographicHash::Sha512:
                // TODO: Implement SHA512 hash
                break;
            default:
                // Invalid algorithm
                break;
        }
    
        std::stringstream ss;
        ss << std::hex << std::uppercase << std::setfill('0');
        for (unsigned char h : hash) {
            ss << std::setw(2) << static_cast<unsigned int>(h);
        }
        result = ss.str();
        return result;
    }
    

    这个示例代码使用了OpenSSL库来实现MD5哈希算法。我们可以传递一个字符串作为输入和所需的算法,然后返回一个十六进制字符串作为哈希结果。

    要使用这个函数来替代上面的Qt代码,可以这样做:

    std::string ba = "your input string";
    std::string ret = QCryptographicHash(ba, QCryptographicHash::Md5);
    

    请注意,这个函数只实现了MD5算法。如果您需要其他哈希算法,您需要根据需要实现它们,并将它们添加到switch语句中。


    如果以上回答对您有所帮助,点击一下采纳该答案~谢谢

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 8月2日
  • 已采纳回答 7月25日
  • 创建了问题 7月24日

悬赏问题

  • ¥15 the testing results of the whole dataset is empty
  • ¥15 can问题,往哥解决
  • ¥15 FFmpeg 成功推流到 Nginx RTMP 服务器但无法用 ffplay 或 VLC 播放
  • ¥15 请修改以下C语言代码使其能正确输出最短路径
  • ¥20 抖音商城拉码器安卓报错求解决办法或者有新的拉码脚本也可以介绍一下
  • ¥15 MPLAB IDE V2.35 报错make[2]: *** [build/default/production/_ext/1472/MSSP_I2C.p1] Error 1
  • ¥15 Unity2D URP项目TextMeshPro(3D)无法显示文字
  • ¥15 新唐M451 DTMF检测和发送代码修改
  • ¥15 在国外文献网站里点击view pdf 加载异常缓慢甚至加载不出来。
  • ¥65 python批量提取发票的信息