#!/usr/bin/perl
#
# nrot13 - A configurable encryption algorithm: NROT13. Perl.
#
# This implements a new configurable encryption algorithm, NROT13. 
#  This is similar to the 3ROT13 algorithm, a symmetric stateless 
#  keyless cypher, however this allows the user to customise the 
#  number of cycles. For example, 3ROT13 can be used, as well as
#  9ROT13 and even the supersymmetric 31ROT13.
#
# WARNING: Due to US Export regulations NROT13 should not be used
#  at cycles greater than 1024ROT13. Check encryption legislation 
#  in your country before use.
#
# 17-Jan-2005	ver 1.00
#
# USAGE: nrot13 -n num { -d | -e }
#	nrot13 -n 3 -e < infile > outfile	# encrypt, 3rot13
#	nrot13 -n 3 -d < infile > outfile	# decrypt, 3rot13
#
# SEE ALSO: 3rot13, http://www.brendangregg.com/specials.html
#
# THANKS: Gunther Feuereisen
#
# NOTE: even numbered cycles produce a non-optimal output that may
#  not be suitable for millitary applications.
#
# COPYRIGHT: Copyright (c) 2004 Brendan Gregg.
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#  (http://www.gnu.org/copyleft/gpl.html)
#
# 17-Jan-2005	Brendan Gregg	Created this.


#
#  Process Command Line Arguments
#
use Getopt::Std;
getopts('den:') || &usage();
$number = $opt_n;
$direction = "-e" if $opt_e;
$direction = "-d" if $opt_d;
&usage if $direction eq "";
&usage if $number == 0;


#
#  Encryption
#
if ($direction eq "-e") {
	while ($plaintext = <STDIN>) {
		$cyphertext = $plaintext;
		for $cycle (1..$number) {
			# ROT13,
			$cyphertext =~ tr/a-zA-Z/n-za-mN-ZA-M/;
		}
		print $cyphertext;
	}
	exit(0);
}

#
#  Decryption
#
if ($direction eq "-d") {
	while ($cyphertext = <STDIN>) {
		$plaintext = $cyphertext;
		for $cycle (1..$number) {
			# ROT13,
			$plaintext =~ tr/a-zA-Z/n-za-mN-ZA-M/;
		}
		print $plaintext;
	}
	exit(0);
}

#
#  Subroutines
#
sub usage {
	print STDERR "USAGE: nrot13 -n num { -d | -e } < infile > outfile\n";
	print STDERR "      nrot13 -n num -e < in > out	# encrypt\n";
	print STDERR "      nrot13 -n num -d < out > in	# decrypt\n";
	exit(1);
}
