From fe4b2e03dc7b63b8e0de6d6a3f950feeb6fe7c9a Mon Sep 17 00:00:00 2001 From: Philippe Pepos Petitclerc Date: Thu, 5 Nov 2015 14:22:28 -0500 Subject: [PATCH] Introduced xoring of String and a sequence of Bytes Signed-off-by: Philippe Pepos Petitclerc --- lib/crypto.nit | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) 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 -- 1.7.9.5