Task

Implement a   Vigenère cypher,   both encryption and decryption.

The program should handle keys and text of unequal length,
and should capitalize everything and discard non-alphabetic characters. 

(If your program handles non-alphabetic characters in another way,
make a note of it.)



Related tasks

   Caesar cipher
   Rot-13
   Substitution Cipher


 
bundle Default {
   class VigenereCipher {
      function : Main(args : String[]) ~ Nil {
         key := "VIGENERECIPHER";
         ori := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
         enc := encrypt(ori, key);
         IO.Console->Print("encrypt: ")->PrintLine(enc);
         IO.Console->Print("decrypt: ")->PrintLine(decrypt(enc, key));
      }
 
      function : native : encrypt(text : String, key : String) ~ String {
         res := "";
         text := text->ToUpper();
         j := 0;
 
         each(i : text) {
            c := text->Get(i);
            if(c >= 'A' & c <= 'Z') {
               res->Append(((c + key->Get(j) - 2 * 'A') % 26 + 'A')->As(Char));
               j += 1;
               j := j % key->Size();
            };
        };
 
        return res;
      }
 
      function : native : decrypt(text : String, key : String) ~ String {
         res := "";
         text := text->ToUpper();
         j := 0;
 
         each(i : text) {
            c := text->Get(i);
            if(c >= 'A' & c <= 'Z') {
               res->Append(((c - key->Get(j) + 26) % 26 + 'A')->As(Char));
               j += 1;
               j := j % key->Size();
            };
         };
 
         return res;
      }
   }
}
 