使用OpenSSL库在C ++中生成SHA-3哈希

时间:2018-07-02 22:37:56

标签: openssl documentation sha-3

我已经广泛搜索了一个代码示例,该示例使用OpenSSL最近实现的SHA-3算法进行哈希处理,但找不到任何示例。在SHA-1和SHA-3上有代码示例,但是在库文件夹中快速搜索后发现OpenSSL v1.1.1中甚至没有SHA3函数名称?

我到处搜索过,但这是相对较新的信息,因此我无法找到有关新算法的任何信息。

我发现这个线程Generate SHA hash in C++ using OpenSSL library涵盖了SHA-1和SHA-2,但是该库中实际上没有SHA3函数-Keccak1600看起来像SHA-3的名字吗?

3 个答案:

答案 0 :(得分:0)

此页面上有一些用于生成哈希的通用示例代码:

https://wiki.openssl.org/index.php/EVP_Message_Digests

该特定代码生成SHA256哈希。要将其转换为使用SHA3,请将EVP_sha256()的两个实例替换为EVP_sha3_224()EVP_sha3_256()EVP_sha3_384()EVP_sha3_512()中的一个。

答案 1 :(得分:0)

我写了一个简单的示例,该示例使用openssl SHA-3实现来计算从stdin读取的所有数据的摘要。 用命令行参数指定SHA-3摘要长度。 在Linux Parrot(基于Debian的发行版),libssl-dev 1.1.1c-1上进行了测试。

Link to the repository

或者这是源代码:

#include <openssl/evp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
/*
 * building on Debian requires libssl-dev package (sudo apt install libssl-dev)
 */

#define BUF_SIZE 1024

#define HANDLE_ERROR(msg) { fprintf(stderr, "%s\n", msg); exit(EXIT_FAILURE); }
#define HANDLE_ERROR2(msg, mdctx) { fprintf(stderr, "%s\n", msg); EVP_MD_CTX_destroy(mdctx); exit(EXIT_FAILURE); }

int main(int argc,  char * const argv[]) {

    int opt;
    char * endptr;
    char buffer[BUF_SIZE];
    int bytes_read;

    EVP_MD_CTX * mdctx;
    int val;
    unsigned char * digest;
    unsigned int digest_len;
    EVP_MD * algo = NULL;

    while ((opt = getopt(argc, argv, "t:")) != -1) {
        switch (opt) {
        case 't':
            errno = 0;

            val = strtol(optarg, &endptr, 10);

            if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
                    || (errno != 0 && val == 0)) {
                perror("Wrong value for t parameter");
                exit(EXIT_FAILURE);
            }

            if (endptr == optarg) {
                fprintf(stderr, "No value was found for t parameter\n");
                exit(EXIT_FAILURE);
            }

            switch (val) {
            case 224:
                algo = EVP_sha3_224();
                break;
            case 256:
                algo = EVP_sha3_256();
                break;
            case 384:
                algo = EVP_sha3_384();
                break;
            case 512:
                algo = EVP_sha3_512();
                break;
            default:
                fprintf(stderr,"Wrong value for t parameter (valid values: 224, 256, 384, 512)");
                exit(EXIT_FAILURE);
            }

            break;
        default: /* '?' */
            fprintf(stderr, "Usage: %s [-t sha3_size]\n"
                    "Example program which calculates SHA-3 hash of data read from stdin.\n"
                    "Uses openssl implementation of SHA-3 algorithm.\n"
                    "sha3_size can be: 224, 256, 384, 512. Default is 256.\n",
                    argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    if (algo == NULL) {
        algo = EVP_sha3_256();
    }


    if ((mdctx = EVP_MD_CTX_create()) == NULL) {
        HANDLE_ERROR("EVP_MD_CTX_create() error")
    }

    // initialize digest engine
    if (EVP_DigestInit_ex(mdctx, algo, NULL) != 1) { // returns 1 if successful
        HANDLE_ERROR2("EVP_DigestInit_ex() error", mdctx)
    }

    while ((bytes_read = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0) { // read returns 0 on EOF, -1 on error
        // provide data to digest engine
        if (EVP_DigestUpdate(mdctx, buffer, bytes_read) != 1) { // returns 1 if successful
            HANDLE_ERROR2("EVP_DigestUpdate() error", mdctx)
        }

    }

    if (bytes_read == -1) {
        perror("read error");
        exit(1);
    }

    digest_len = EVP_MD_size(algo);

    if ((digest = (unsigned char *)OPENSSL_malloc(digest_len)) == NULL) {
        HANDLE_ERROR2("OPENSSL_malloc() error", mdctx)
    }

    // produce digest
    if (EVP_DigestFinal_ex(mdctx, digest, &digest_len) != 1) { // returns 1 if successful
        OPENSSL_free(digest);
        HANDLE_ERROR2("EVP_DigestFinal_ex() error", mdctx)
    }

    for (int i = 0; i < digest_len; i++) {
        printf("%02x", digest[i]);
    }

    OPENSSL_free(digest);
    EVP_MD_CTX_destroy(mdctx);

    return 0;
}

答案 2 :(得分:0)

在已安装# frozen_string_literal: true require 'axlsx' wb = xlsx_package.workbook wb.styles do |s| wb.add_worksheet(name: 'test') do |sheet| end end 的Ubuntu 18.04上:

//main.cpp

#include <iostream>
#include <vector>
#include <sstream> //for std::ostringstream
#include <iomanip> //for std::setw, std::hex, and std::setfill
#include <openssl/evp.h> //for all other OpenSSL function calls
#include <openssl/sha.h> //for SHA512_DIGEST_LENGTH

//helper function to print the digest bytes as a hex string
std::string bytes_to_hex_string(const std::vector<uint8_t>& bytes)
{
    std::ostringstream stream;
    for (uint8_t b : bytes)
    {
        stream << std::setw(2) << std::setfill('0') << std::hex << static_cast<int>(b);
    }
    return stream.str();
}

//perform the SHA3-512 hash
std::string sha3_512(const std::string& input)
{
    uint32_t digest_length = SHA512_DIGEST_LENGTH;
    const EVP_MD* algorithm = EVP_sha3_512();
    uint8_t* digest = static_cast<uint8_t*>(OPENSSL_malloc(digest_length));
    EVP_MD_CTX* context = EVP_MD_CTX_new();
    EVP_DigestInit_ex(context, algorithm, nullptr);
    EVP_DigestUpdate(context, input.c_str(), input.size());
    EVP_DigestFinal_ex(context, digest, &digest_length);
    EVP_MD_CTX_destroy(context);
    std::string output = bytes_to_hex_string(std::vector<uint8_t>(digest, digest + digest_length));
    OPENSSL_free(digest);
    return output;
}

int main()
{
    std::string output = sha3_512(std::string("abcdef"));
    std::cout << output << "\n";
    return 0;
}

libssl-dev-lssl链接以编译此代码:

-lcrypto

输出:

/usr/bin/g++-10 main.cpp -lssl -lcrypto

使用此工具验证输出:https://emn178.github.io/online-tools/sha3_512.html