ChristofferJoergensen ChristofferJoergensen - 1 month ago 9
Ruby Question

How to convert a hexadecimal string back to it's 'SecureRandom.random_bytes' binary?

In Ruby, I can create a 16 byte binary and convert it to a hexadecimal string:

key = SecureRandom.random_bytes(16) # => "hN\xDB\xAD\xAF\xB3R\xC0`\xB19\x1D\x19.\xD3I"
hex_key = key.each_byte.map { |byte| '%02x' % byte }.join # => "684edbadafb352c060b1391d192ed349"


In PHP and Javascript I can convert the the hexadecimal string back to it's 16 byte binary.

PHP:

<?php
hex2bin("684edbadafb352c060b1391d192ed349");
?>


Javascript via CryptoJS:

CryptoJS.enc.Hex.parse("684edbadafb352c060b1391d192ed349");


But how do I convert the hexadecimal string back to it's 16 byte binary, using Ruby?

Jay Jay
Answer

Is this what you are looking for?

[str].pack('H*').bytes.to_a

or just

[str].pack('H*')