dc wrote:
> hi -
> 
>> > any other suggested alternatives to this approach?
>>
>> Let your key be an integer.  XOR each byte (or set of bytes) in the
>> string by the integer to encode.  To decode, XOR them again.  Let me
>> know if you'd like code.  (Actually, I'd be interested to see other
>> people's implementations. ;)
> 
> I googled a bit and found something in this direction, but cant get
> the reverse of it
> (at least not a working version!)

The point of the technique is that if you get it working one way, it 
automatically works the other way, too.  The same function encrypts and 
decrypts.

> Would appreciate a working fragment...
> 
> 
>        def encr str
>            key = "ABC123abc123ABC456ABC123abc"  # long enough?

Depends on how strong you need the encryption to be. :)

>            result = (0..str.length-1).collect { |i|
>                $stderr.puts("#{i} #{str[i]}")
>                str[i] ^ key[i]
>            }
>            result.pack("C*")
>            return result
>        end
> 
> does the key have to be an integer for XOR ( ^ operator ) to work?

No, but the XOR operation for whatever object type you use has to undo 
itself when applied an even number of times.  A plain old bit-pattern 
works nicely, and bit-patterns are easy to visualize as integers.

Here's a quick example that uses an 8-bit key for simplicity.  To use a 
larger key of N bits, you'll probably want to break it into (N / 8 + (N 
% 8 == 0 ? 0 : 1)) bytes, and rotate which byte you're XORing as you 
walk through the bytes of the string.

def encr(s, k)
     r = ''
     s.each_byte { |b| r += (b ^ k).chr }
     r
end

s = "hello"
k = 42

e = encr(s, k)
puts e # "BOFFE" on ASCII-like machines.
puts encr(e, k) # Re-creates the original string.