From: Alex Young Date: 2007-01-29T09:25:04+09:00 Subject: Re: "a string".xor("another string") Erik Veenstra wrote: > You're padding the shortest string with low values. When using > XOR to encrypt a string (my goal...), uh, you're not encrypting > most of the data: > > "very long secret data".xor("secret") # ==> "\005\000\021\vE\030ong > secret data" > > The secret key should be repeated several times, so every byte > in the data gets XOR'ed. Robert's solution can be modified: > irb(main):008:0> a="a string" > => "a string" > irb(main):009:0> b="another string" > => "another string" > irb(main):014:0> s="";[a.size, b.size].max.times {|i| s << ((a[i]||0) ^ (b[i]||0))} > => 14 This becomes: s="" [a.size, b.size].max.times {|i| s << ((a[i%a.size]||0)^(b[i%b.size]||0)) } That takes care of the looping. << doesn't create a new string (at least, not to my knowledge...) but it will (I presume) cause reallocation. This should get around that: s = " " * [a.size,b.size].max [a.size, b.size].max.times {|i| s[i] = ((a[i%a.size]||0)^(b[i%b.size]||0)) } No idea if it's faster or slower, and it's past my bedtime so I'm not going to benchmark it right now :-) -- Alex