Introduced xoring of String and a sequence of Bytes
authorPhilippe Pepos Petitclerc <ppeposp@gmail.com>
Thu, 5 Nov 2015 19:22:28 +0000 (14:22 -0500)
committerPhilippe Pepos Petitclerc <ppeposp@gmail.com>
Thu, 5 Nov 2015 19:55:04 +0000 (14:55 -0500)
Signed-off-by: Philippe Pepos Petitclerc <ppeposp@gmail.com>

lib/crypto.nit

index 011347d..73488d8 100644 (file)
@@ -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