SHA256 Output Is Not Always 32 Bytes About 25% Of The Time

Overview

I’m attempting to use mbedtls within a project to hash an ECC public key using sha256, and then base58 encode it. I’m running into an issue were about 25% of the time the output from mbedtls_sha256_ret is not always 32 bytes.

I’ve observed the output be anything from 0 bytes, up to 38 bytes. While researching the issue I found this thread from the old forums. I tried the suggestions, and made sure to avoid using strlen however the issue still remains.

For example here is the following output

public key length: 178 <-- expected
public key hash length: 32 <-- expected
digest length: 32 <-- exepected
multihash buffer length: 34 ,-- expected
QmXTUk1HEGdrtiigAyMBqUzF2B9YzWSp8FYfZvp6Dfpq6F <-- expected

Now running the same test suite again a few more times, and I get this

public key length: 178 <-- expected
public key hash length: 27 <-- UNEXPECTED - sha256 output is 27 bytes as opposed to 32
digest length: 27 <-- UNEXPECTED
multihash buffer length: 29 <-- UNEXPECTED
pgWvTzePQ6Ge5JUaqJQfDNeM91F93oxP9yZZs1Q <-- UNEXPECTED
  1. Here is the CMocka test that is being problematic
  2. Here is the function that is responsible for doing the hasing
  3. Here is the call to the hash function which occasionally returns bad output

Version Information

  • gcc: gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0
  • mbedtls: v2.23.0
  • os kernel: Linux gray 5.4.0-7634-generic #38~1592497129~20.04~9a1ea2e-Ubuntu SMP Fri Jun 19 22:43:37 UTC x86_64 x86_64 x86_64 GNU/Linux

/etc/lsb-release:

DISTRIB_ID=Pop
DISTRIB_RELEASE=20.04
DISTRIB_CODENAME=focal
DISTRIB_DESCRIPTION="Pop!_OS 20.04 LTS"

I did some more digging and it appears that its not a bug with mbedtls, instead it is was an issue with the SHA256 output having a 0 in it, and the base encoding library I used was not able to handle that situation