Search code examples
hashopensslshadigestmessage-digest

OpenSSL: can output size of EVP_DigestFinal_ex be greater than the digest size?


OpenSSL EVP_DigestFinal_ex has the following documentation:

"EVP_DigestFinal_ex() retrieves the digest value from ctx and places it in md. If the s parameter is not NULL then the number of bytes of data written (i.e. the length of the digest) will be written to the integer at s, at most EVP_MAX_MD_SIZE bytes will be written."

Signature:

int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s);

Are there any cases where the digest length will be greater than the output size of the digest yet smaller than EVP_MAX_MD_SIZE. i.e. for SHA-1 digest, I get an output which is greater than 20bytes?


Solution

  • Relevant source code from OpenSSL crypto/evp/digest.c:

        OPENSSL_assert(ctx->digest->md_size <= EVP_MAX_MD_SIZE);
        ret = ctx->digest->final(ctx, md);
        if (size != NULL)
           *size = ctx->digest->md_size;
    

    where size is your desired output digest size, and digest is a const structure which in case of SHA1 is being defined in crypto/evp/m_sha1.c:

    static const EVP_MD sha1_md = {
         NID_sha1,
         NID_sha1WithRSAEncryption,
         SHA_DIGEST_LENGTH
    

    md_size is the third member of this structure, so it always will be SHA_DIGEST_LENGTH which is equal to 20