Reputation: 1119
I have a string password
that contains this
\x79\x6F\x75\x63\x61\x6E\x74\x68\x61\x78\x6D\x65
I want to print these as ASCII characters. I created this string by taking the hex characters and adding the \x
in front of them. puts(password)
does not work. However, when I do something like:
shellcode = "\x65\x61"
puts(shellcode)
it works just fine. What am I doing wrong?
Upvotes: 4
Views: 4547
Reputation: 40543
Strings are a strange beast in Ruby, and their handling changed subtly with Ruby 1.9, which somewhat complicates matters.
If you have that string either created with single quotes and coming from some other source (say a DB), then if you inspect
it you will see:
"\\x79\\x6F\\x75\\x63\\x61\\x6E\\x74\\x68\\x61\\x78\\x6D\\x65"
You can process that with a wee bit of list processing:
s.scan(/\\x(..)/).map{|a| a.first.to_i(16).chr}.join
# => "youcanthaxme"
To explain:
We extract the individual components by taking the two characters following an \\x
(scan(/\\x(..)/)
): [["79"], ["6F"], ["75"], ["63"], ["61"], ["6E"], ["74"], ["68"], ["61"], ["78"], ["6D"], ["65"]]
For each element of the list (map
), we turn it into an integer (a.first.to_int(16)
): [121, 111, 117, 99, 97, 110, 116, 104, 97, 120, 109, 101]
Then we find the ascii character that corresponds to that ascii value (chr
): ["y", "o", "u", "c", "a", "n", "t", "h", "a", "x", "m", "e"]
Then we join
them all together: "youcanthaxme"
Upvotes: 5