Question

I need to convert this OpenSSL::PKey::DH#compute_key (aString type) to integer (documentation). These are the tests I ran to check the format output by compute_key.

...
...
shared_key = dh1.compute_key(public_key)
puts "1"
puts shared_key
puts "2"
puts shared_key.to_s
puts "3"
puts shared_key.inspect
puts "4"
puts shared_key.to_yaml

These output:

1
���`���,�L@�9�������Q���?�J����
2
���`���,�L@�9�������Q���?�J����
3
"\xD2\xBD\xBA`\xBC\xB1\xA6\x11,\xE9L@\x8C9\xA9\xAF\x88\xFD\x8F\xD9\x92Q\xE9\x93\x92?\xBCJ\xFB\xD2\xAC\xEE"
4
--- !binary |-
  0r26YLyxphEs6UxAjDmpr4j9j9mSUemTkj+8SvvSrO4=

I'm expecting an integer value of

 95320918630576230557892713337132753026878147296634144208600768328265758846190

if formatted correctly. I'm guessing on converting the whole string/data outputted by compute_key to binary first, then into an integer. But I'm not too sure if that's the right approach. I also tried String::unpack, but it didn't give me the expected format (or perhaps my input parameters to unpack is not right). Please help.

Was it helpful?

Solution

OK, I have managed to get the number, however I've no idea why it behaves this way:

Step 1. Get binary representation of the string:

shared_key.unpack('B*').first

Step 2. Convert this into integer:

shared_key.unpack('B*').first.to_i(2)

#=>  95320918630576230557892713337132753026878147296634144208600768328265758846190 

OTHER TIPS

Try following

shared_key.encode( "UTF-8", "binary", :invalid => :replace, :undef => :replace).unpack("B*").first.to_i(2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top