Brandon Yarbrough
Brandon Yarbrough

Reputation: 38399

Convert a string of 0-F into a byte array in Ruby

I am attempting to decrypt a number encrypted by another program that uses the BouncyCastle library for Java.

In Java, I can set the key like this: key = Hex.decode("5F3B603AFCE22359");

I am trying to figure out how to represent that same step in Ruby.

Upvotes: 18

Views: 20395

Answers (2)

Nakilon
Nakilon

Reputation: 35102

To get Integer — just str.hex. You may get byte array in several ways:

str.scan(/../).map(&:hex)
[str].pack('H*').unpack('C*')
[str].pack('H*').bytes.to_a

See other options for pack/unpack and examples (by codeweblog).

Upvotes: 41

ReWrite
ReWrite

Reputation: 2708

For a string str:

"".tap {|binary| str.scan(/../) {|hn| binary << hn.to_i(16).chr}}

Upvotes: 3

Related Questions