On Jul 1, 2010, at 11:34 AM, Joshua Mckinney wrote:
> Rob Biedenharn wrote:
>> On Mar 24, 2009, at 2:35 AM, Felipe Coury wrote:
>>> Posted via http://www.ruby-forum.com/.
>>
>> I'm glad you got it.  Your key-building function doesn't need to be
>> quite so complex:
>>
>> def mysql_key2(key)
>>   final_key = "\0" * 16
>>   key.length.times do |i|
>>     final_key[i%16] ^= key[i]
>>   end
>>   final_key
>> end
>>
>> Hardly needs any comments now ;-)  Just a pointer to the MySQL doc
>> perhaps.
>>
>> irb> mkey2 = mysql_key2(key)
>> => "dp&!{\021?pK?G!8[r."
>> irb> mkey == mkey2
>> => true
>>
>> -Rob
>>
>> Rob Biedenharn    http://agileconsultingllc.com
>> Rob / AgileConsultingLLC.com
>
>
> Having no luck with this. Getting the following error when generating
> they key in 1.8.7 and 1.9.1. Any help would be much appreciated.
>
> ruby-1.9.1-p378 > key = "test_key"
> => "test_key"
> ruby-1.9.1-p378 >     final_key = "\0" * 16
> => "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
> ruby-1.9.1-p378 >     key.length.times do |i|
> ruby-1.9.1-p378 >           final_key[i%16] ^= key[i]
> ruby-1.9.1-p378 ?>      end
> NoMethodError: undefined method `^' for "\x00":String
>  from (irb):89:in `block in irb_binding'
>  from (irb):88:in `times'
>  from (irb):88
>
> ruby-1.9.1-p378 >     final_key
> => "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

Because in Ruby 1.8.6, "hello"[0] is 104, but in 1.8.7 and 1.9.x,  
"hello"[0] is "h"

Change that line to:

final_key[i%16] = (final_key[i%16].ord ^ key[i].ord).chr

And you should get the right answer:

irb> x="hello"
=> "hello"
irb> x[0] = (x[0].ord ^ 0x20).chr
=> "H"
irb> x
=> "Hello"

String#ord gives the Fixnum value of a single-character string.
Fixnum#chr gives the single-character String whose #ord is the Fixnum

(I'm sure the actual docs say that better ;-)

-Rob

Rob Biedenharn
http://agileconsultingllc.com
	Rob / AgileConsultingLLC.com
http://gaslightsoftware.com
	rab / GaslightSoftware.com