lib: Update libs to use correctly ascii and code_point
[nit.git] / examples / rosettacode / vignere_cipher.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 # This program is public domain
3
4 # Task: Vigenère cipher
5 #
6 # See: <http://rosettacode.org/wiki/Vigenère_cipher>
7 module vignere_cipher
8
9 fun encrypt(src, key: String): String do
10 var out = new Buffer
11 var j = 0
12
13 for i in [0..src.length - 1] do
14 var c = src[i]
15
16 if c >= 'a' and c <= 'z' then
17 c = c.to_upper
18 else if c < 'A' or c > 'Z' then
19 continue
20 end
21
22 out.add(((c.ascii + key[j].ascii - 2u8 * 'A'.ascii) % 26u8 + 'A'.ascii).ascii)
23 j = (j + 1) % key.length
24 end
25
26 return out.to_s
27 end
28
29 fun decrypt(src, key: String): String do
30 var out = new Buffer
31 var j = 0
32
33 for i in [0..src.length - 1] do
34 var c = src[i]
35
36 if c >= 'a' and c <= 'z' then
37 c = c.to_upper
38 else if c < 'A' or c > 'Z' then
39 continue
40 end
41
42 out.add(((c.ascii - key[j].ascii + 26u8) % 26u8 + 'A'.ascii).ascii)
43 j = (j + 1) % key.length
44 end
45
46 return out.write_to_string
47 end
48
49 # Main part
50 var str = "All your base are belong to us"
51 var key = "CRYPTONIT"
52 var code = encrypt(str, key)
53 var decode = decrypt(code, key)
54
55 print "Text: " + str
56 print "Key : " + key
57 print "Code: " + code
58 print "Back: " + decode