3
$\begingroup$

Is it safe and secure to use a function like bin2hex (which converts binary data to hexadecimal) on the binary output of functions like openssl_random_pseudo_bytes and mcrypt_create_iv?

Meaning: can I use the hexadecimal output instead of the raw binary data, or is there some kind of security risk involved when doing so?

$\endgroup$
6
$\begingroup$

An initialization vector is, in fact, always binary. It's just random bits. So, if you choose to encode those bits as a hexadecimal string for ease of storage or transportation, that is fine. However, since it is the binary that is the IV, you will need to decode it back from hexadecimal to a binary value before using it in the decryption process.

As a note, you would certainly not want to use the binary values of the individual characters in a hexadecimal string as an IV, as that would limit you to a tiny set of possible IVs, much smaller than the space you need to generate IVs securely.

$\endgroup$
  • $\begingroup$ An IV isn't necessarily always random bits. In some modes, it can be a simple counter. That said, the gist of your answer is correct: you should only ever provide an IV, key, or ciphertext in the format expected by your cryptographic library; usually, that is in the form of raw binary data. Encode this data however you wish for storage and transport, but always convert it back before sending it through cryptographic routines. $\endgroup$ – Stephen Touset Jan 8 '16 at 22:57
  • 1
    $\begingroup$ @StephenTouset Sure...I would generally use the term nonce in that case, rather than IV, but that's splitting hairs. $\endgroup$ – Xander Jan 8 '16 at 22:58
  • 1
    $\begingroup$ @StephenTouset Sorry to say so, but I tend to disagree. An IV is a nonce (number only used once) with an additional requirement: it must be chosen in a nonpredictable way (aka “cryptographically random”). Since the Q specifically asks about random IVs, pointing towards non-random nonces – eg as used in CTR-mode – seems a bit (let’s just call it) wrong. After all, IV randomness does make a difference (becoming apparent when looking at things like potential protection against capture-replay attacks, which a random IV can’t offer unless you “store-to-compare-later” every IV you ever used). $\endgroup$ – e-sushi Jan 9 '16 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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