1

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?

Cjoerg
  • 1,271
  • 3
  • 21
  • 63
  • Possible duplicate of [What does \["string"\].pack('H\*') mean?](http://stackoverflow.com/questions/17623668/what-does-string-packh-mean) – Artjom B. Oct 19 '16 at 19:53

1 Answers1

6

Is this what you are looking for?

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

or just

[str].pack('H*')
Jay
  • 2,656
  • 1
  • 16
  • 24