#!/usr/bin/perl -w # encode.pl - Don Yang (uguu.org) # # Use uppercase letters to encrypt, lowercase to decrypt: # ./encode0.pl KEY < plaintext.txt > ciphertext.txt # ./encode0.pl key < ciphertext.txt > plaintext.txt # # Uppercase/lowercase is just a convention, but using this convention # makes it easier to decrypt by hand since shifting letters in the # positive direction is easier. # # 2015-05-22 use strict; # Get key from command line argument if( $#ARGV < 0 ) { die "$0 \n"; } my $key = shift @ARGV; $key =~ s/[^a-zA-Z]//g; if( length($key) == 0 ) { $key = "a"; } # Transform input my $index = 0; while( my $line = <> ) { foreach my $i (unpack 'C*', $line) { my $c = chr($i); if( $c =~ /[a-zA-Z]/ ) { my $k = substr($key, $index++, 1); $index %= length($key); # Add offset for lowercase character in key, subtract offset # for uppercase character. my $offset = ($k eq lc($k)) ? ord($k) - ord('a') : ord('A') - ord($k) + 26; $c = ($c eq lc($c)) ? chr(($i - ord('a') + $offset) % 26 + ord('a')) : chr(($i - ord('A') + $offset) % 26 + ord('A')); } print $c; } }