################################################################
# kasiski.pl : Kasiski's search for repeated substrings        #
#    Input from STDIN : ciphertext (or any text if you like)   #
#    Output to STDOUT : 4 character substrings of input text   #
#                         with index of 1st and 2nd occurrence,#
#                         one per line.                        #
# Theory and application: Look at any book in classical        #
#   cryptology, chapter on polyalphabetic substitution.        #
#--------------------------------------------------------------#
# For short cipher texts it makes sense to serch for repeated  #
# 3 character strings. If yo want so, replace the 4 dots in    #
# parentheses in the while condition with 3 dots.              #
#--------------------------------------------------------------#
# Klaus Pommerening 9. Juni 1997, 18. Dezember 1999            #
#                                                              #
# This program is freeware. Use it as you like.                #
# Usual disclaimers apply.                                     #
################################################################

require "auxcrypt.pl";           # Use &gettext.

$text = &gettext;                # Get input text.

$pos = 0;                        # Index of remaining substring.
while ($text =~ /(....).*\1/) {  # While there is a repeated 4
                                 #   character substring:
  $i = index($text, $1);         # Note its position,
  $pos += $i;                    # calculate position in 
                                 #   original text.
  print "$1 at index $pos";      # Cry heureka!
  $i++;                          # Go to next position,
  $text = substr($text, $i);     # cut off head of remaining
  $pos++;                        #   text and adjust index.
  $i = index($text, $1);         # Search for 2nd occurrence.
  print " and ", $pos + $i, " - difference = ", $i+1, "\n";
                                 # Tell what you found.
  }
