Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #307 XOR encrypt/decrypt string

Create a function that XOR encrypts/decrypts a string

sub xor_crypt {
    my ($b, $k) = @_;
    return $b ^ $k;
}
sysutils
encrypted := xorstring(key, original);
from itertools import cycle
def xor(data, key):
	return ''.join(chr(ord(x)^ord(y)) for x,y in zip(data, cycle(key)))
def xor_string(str, key)
  ords = key.chars.map(&:ord).cycle
  str.chars.zip(ords).inject(""){|res, (c,o)| res << (c.ord ^ o) }
end
fn xor(s: Vec<u8>, key: &[u8]) -> Vec<u8> {
    let mut b = key.iter().cycle();
    s.into_iter().map(|x| x ^ b.next().unwrap()).collect()
}

New implementation...
< >
anonymous