Skip to content

BinaryToHex loop ignores length parameter, hardcodes SHA_DIGEST_LENGTH #10840

@Al2Klimov

Description

@Al2Klimov

File: lib/base/tlsutility.cpp · Function: BinaryToHex

Problem

BinaryToHex(const unsigned char* data, size_t length) accepts an arbitrary
length but the loop body iterates over the hardcoded constant
SHA_DIGEST_LENGTH (20) instead:

String BinaryToHex(const unsigned char* data, size_t length) {
    static const char hexdigits[] = "0123456789abcdef";

    String output(2 * length, 0);
    for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {   // ← should be `length`
        output[2 * i]     = hexdigits[data[i] >> 4];
        output[2 * i + 1] = hexdigits[data[i] & 0xf];
    }

    return output;
}

Both current callers happen to pass exactly 20 bytes, so nothing breaks today.
But the function is declared in the public header lib/base/tlsutility.hpp and
looks like the intended generic replacement for the hand-rolled sprintf hex
loops elsewhere in the codebase. The next caller who passes a different length
(SHA-256 → 32 bytes, HMAC token → 16 bytes, …) will get silently wrong output
or out-of-bounds behaviour with no compiler warning.

Metadata

Metadata

Assignees

Labels

core/qualityImprove code, libraries, algorithms, inline docsgood first issueGood for newcomers

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions