RosettaCode: Vignere
authorSimon Zeni <simonzeni@gmail.com>
Tue, 23 Jun 2015 00:11:24 +0000 (20:11 -0400)
committerJean Privat <jean@pryen.org>
Tue, 23 Jun 2015 00:13:27 +0000 (20:13 -0400)
Close #1479

examples/rosettacode/vignere_cipher.nit [new file with mode: 0644]
tests/sav/vignere_cipher.res [new file with mode: 0644]

diff --git a/examples/rosettacode/vignere_cipher.nit b/examples/rosettacode/vignere_cipher.nit
new file mode 100644 (file)
index 0000000..73a3f41
--- /dev/null
@@ -0,0 +1,58 @@
+# This file is part of NIT ( http://www.nitlanguage.org ).
+# This program is public domain
+
+# Task: Vigenère cipher
+#
+# See: <http://rosettacode.org/wiki/Vigenère_cipher>
+module vignere_cipher
+
+fun encrypt(src, key: String): String do
+       var out = new Buffer
+       var j = 0
+
+       for i in [0..src.length - 1] do
+               var c = src[i]
+
+               if c >= 'a' and c <= 'z' then
+                       c = c.to_upper
+               else if c < 'A' or c > 'Z' then
+                       continue
+               end
+
+               out.add(((c.ascii + key[j].ascii - 2 * 'A'.ascii) % 26 + 'A'.ascii).ascii)
+               j = (j + 1) % key.length
+       end
+
+       return out.to_s
+end
+
+fun decrypt(src, key: String): String do
+       var out = new Buffer
+       var j = 0
+
+       for i in [0..src.length - 1] do
+               var c = src[i]
+
+               if c >= 'a' and c <= 'z' then
+                       c = c.to_upper
+               else if c < 'A' or c > 'Z' then
+                       continue
+               end
+
+               out.add(((c.ascii - key[j].ascii + 26) % 26 + 'A'.ascii).ascii)
+               j = (j + 1) % key.length
+       end
+
+       return out.write_to_string
+end
+
+# Main part
+var str = "All your base are belong to us"
+var key = "CRYPTONIT"
+var code = encrypt(str, key)
+var decode = decrypt(code, key)
+
+print "Text: " + str
+print "Key : " + key
+print "Code: " + code
+print "Back: " + decode
diff --git a/tests/sav/vignere_cipher.res b/tests/sav/vignere_cipher.res
new file mode 100644 (file)
index 0000000..4f03d3d
--- /dev/null
@@ -0,0 +1,4 @@
+Text: All your base are belong to us
+Key : CRYPTONIT
+Code: CCJNHIEJTUVYGXPRTHPXRDNG
+Back: ALLYOURBASEAREBELONGTOUS