Hacker News new | ask | show | jobs
by mynameisbahaa 3329 days ago
I think the programmer should have supplied the length of the "computed_hash" not the "response" which as I understood supplied by the user. Like this : strncmp(computed_hash, response, computed_hash_length)
2 comments

You don't want to use strncmp() for this; aside from the timing attacks it opens up, using strncmp() for these kinds of comparisons implies that the operation you are performing is "string a is a prefix of string b" (or vice-versa).

Even though your example ends up being ok-ish (if the computed hash is a prefix of the response, perhaps it is ok to ignore any trailing junk in the response), intent is important for code quality and maintainability.

In this instance, the operation desired is "string a matches string b", which means strcmp() would be the right solution (ignoring timing attacks).

Of course, since we're talking about sensitive crypto operations here, neither is really the right answer. But in non-crypto contexts, if you want to know if two (valid) strings are the same, just use strcmp().

The "n" and the length argument doesn't automatically make strncmp() "safer" somehow; it is a totally different operation.

Yes. It was hilarious that the poster thought strcmp was the solution...

Though perhaps memcmp with fixed size buffers would be better still, no worrying about null terminated strings.