简体   繁体   中英

EVP_DigestUpdate and “invalid conversion from ‘unsigned char*’ to ‘const char*’”

Here's the example taken from EVP Message Digests on the OpenSSL wiki:

void digest_message(unsigned char *message, unsigned char **digest, unsigned int *digest_len)
{
    EVP_MD_CTX *mdctx;

    if((mdctx = EVP_MD_CTX_create()) == NULL)
        handleErrors();

    if(1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL))
        handleErrors();

    if(1 != EVP_DigestUpdate(mdctx, message, strlen(message)))
        handleErrors();

    if((*digest = (unsigned char *)OPENSSL_malloc(EVP_MD_size(EVP_sha256()))) == NULL)
        handleErrors();

    if(1 != EVP_DigestFinal_ex(mdctx, *digest, digest_len))
        handleErrors();

    EVP_MD_CTX_destroy(mdctx);
}

The problem is when I try to compile it I get the following error:

evp_test.cpp:18:60: error: invalid conversion from ‘unsigned char*’ to ‘const char*’ [-fpermissive]
 if(1 != EVP_DigestUpdate(mdctx, message, strlen(message)))

In file included from /usr/include/c++/5/cstring:42:0

So strlen being called on message causes the error because strlen expects a const char ? Is this because strings are arrays of const chars ?

What should I be doing differently to solve the issue?

It has been fixed:

void digest_message(const unsigned char *message, size_t message_len,
                    unsigned char **digest, unsigned int *digest_len)
{
    EVP_MD_CTX *mdctx;

    if((mdctx = EVP_MD_CTX_create()) == NULL)
        handleErrors();

    if(1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL))
        handleErrors();

    if(1 != EVP_DigestUpdate(mdctx, message, message_len))
        handleErrors();

    if((*digest = (unsigned char *)OPENSSL_malloc(EVP_MD_size(EVP_sha256()))) == NULL)
        handleErrors();

    if(1 != EVP_DigestFinal_ex(mdctx, *digest, digest_len))
        handleErrors();

    EVP_MD_CTX_destroy(mdctx);
}

You were right that strlen needs an array of char , and not an unsigned char or byte .

The bigger problem was the design/engineering. An explicit length parameter was needed because there's no guarantee a byte array is NULL terminated like a C-string. In fact, a byte array might have a few NULLs embedded in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM