Libsodium has some helpers, which allow hexdecimal decoding, encoding and also constant-time string comparison.
So if you use the php binding libsodium-php you obviously also have the native php implementation of bin2hex and hex2bin. The libsodium replacements were introduced because the native implementations are not timing-resistent. So for sensitive data this should be used.

But if you have a library/project where you use libsodium anyway are there any disadvantages of using libsodiums functions even in places where this would not be necessary?
I mean one advantage clearly would that you can prevent to forget to use these timing-save implementations in cases where it is important if you just use it everywhere.


2 Answers 2


Functions often become timing resistant by not using short circuit evaluation. There is conceivably a small performance price to be paid by not using short circuit evaluation.

In reality, this is probably not a bottleneck or serious concern. Edit: It also might be possible that libsodiums function is faster anyways.

I would have commented with this, but I don't have enough rep to comment. There may be more to consider.

  • $\begingroup$ "It also might be possible that libsodiums function is faster anyways." - Indeed I also thought so, because libsodium (also) uses a native C implementation, which is generally quite fast. $\endgroup$
    – rugk
    Commented Jan 14, 2016 at 17:03
  • $\begingroup$ @rugk, if you call it from a higher level language, you go through the bindings which may slow it down. Plus the PHP's internal implementation is in C anyway. Bottom line: speed can go either way, benchmark if you care. $\endgroup$
    – otus
    Commented Mar 4, 2016 at 7:18

The advantage is: You can be quite confident that, if every other bit of the cryptography code you're working with is securely designed and side-channel resistant, you can rest assured that hex encoding/decoding won't introduce new vulnerabilities if you use libsodium's implementation.

And if you throw caution to the wind here, you might be fine. None of the researchers I've talked with have alluded to any practical exploits against cache-timing leaks caused by hex encoding.

Of course, the usual disclaimer applies: Attacks only get better.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.