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


encode[text_String, key_String] :=
 Module[{textCode, keyCode},
  textCode = 
   Cases[ToCharacterCode[
      ToUpperCase@
       text], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;
  keyCode = 
   Cases[ToCharacterCode[
      ToUpperCase@
       key], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65; 
  keyCode = 
   If[Length[textCode] < Length[keyCode], 
    keyCode[[;; Length@textCode]], 
    PadRight[keyCode, Length@textCode, keyCode]];
  FromCharacterCode[Mod[textCode + keyCode, 26] + 65]]
 
decode[text_String, key_String] :=
 Module[{textCode, keyCode},
  textCode = 
   Cases[ToCharacterCode[
      ToUpperCase@
       text], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;
  keyCode = 
   Cases[ToCharacterCode[
      ToUpperCase@
       key], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65; 
  keyCode = 
   If[Length[textCode] < Length[keyCode], 
    keyCode[[;; Length@textCode]], 
    PadRight[keyCode, Length@textCode, keyCode]];
  FromCharacterCode[Mod[textCode - keyCode, 26] + 65]]