18

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.

2 Answers 2

41

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Isn't the .to_a superfluous? If someone cares about performance with huge Strings (10M hex digits): str.scan(/../).map(&:hex): 1.061567s, [str].pack('H*').unpack('C*'): 0.175744s [str].pack('H*').bytes.to_a: 0.149195s
3

For a string str:

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

2 Comments

Nice! It's a style thing, but personally I'd rephrase it as: str.scan(/../).inject(""){|binary,hn| binary << hn.to_i(16).chr}.
Note: str.scan(/../) performs way worse. This might be irrelevant for 'normal' numbers as of 1-16 bytes

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.