From: Philippe Pepos Petitclerc Date: Thu, 5 Nov 2015 19:22:28 +0000 (-0500) Subject: Introduced xoring of String and a sequence of Bytes X-Git-Tag: v0.8~106^2~2 X-Git-Url: http://nitlanguage.org Introduced xoring of String and a sequence of Bytes Signed-off-by: Philippe Pepos Petitclerc --- diff --git a/lib/crypto.nit b/lib/crypto.nit index 011347d..73488d8 100644 --- a/lib/crypto.nit +++ b/lib/crypto.nit @@ -154,6 +154,32 @@ redef class String end return arr.to_s end + + # Returns `self` xored with `key` + # + # The shortest of the two is cycled through until the longest has been + # completely xored. + # + # assert "goodmorning".xor(" ".to_bytes) == "GOODMORNING" + fun xor(key: SequenceRead[Byte]): String do + var xored = new Bytes.empty + var shortest: SequenceRead[Byte] + var longest: SequenceRead[Byte] + + if key.length > self.length then + shortest = self.to_bytes + longest = key + else + shortest = key + longest = self.to_bytes + end + + for i in longest.length.times do + xored.add(longest[i] ^ shortest[i % shortest.length]) + end + + return xored.to_s + end end redef class Int