Sunday, 13 July 2008

Zigzag Cypher

The Zigzag cypher (also known as a Rail Fence is a simple transposition scheme and not very strong, this is just an exercise in tinkering.
First here is the encoder:

#!/usr/bin/perl
$rowlen = @ARGV[0];
$message = @ARGV[1];
if ( @ARGV == 0) {
$message="CHARLIETHEWONDERBUDGIE";
$rowlen =6;
}
$rowlen -- ;
@letter = split '', $message;

$dir =0;
$index =0 ;

for ($r=0;$r<= @letter ;$r++){
@array[$index]=@array[$index].@letter[$r];
if($dir == 0) { $index++; }
if($dir == 1) { $index--; }
if ($index >$rowlen ) {
$dir = 1 ;
$index-=2;
}
if ($index <0) {
$dir=0;
$index+=2;
}
}

for ($r=0;$r<= $rowlen ;$r++){
print @array[$r] ;
}
print "\n";


After some trial and error the decoder

#!/usr/bin/perl

sub unzig {
#adjust for zero-numbering
$rowlen-- ;
@letter= split '', $cryptStr;

for ($r=0;$r <= scalar(@letter) ;$r++){
@array[$r]=" ";
}

$rowIndex =0;
$tempIndex=0;
$arrayLen = @letter-1;
$r=0;
$newrow=0;
while($r <= $arrayLen ){
if ($newrow == 1 ) {
# new row
$rowIndex++;
$tempIndex = $rowIndex;
@array[$tempIndex] = @letter[$r];
if ($rowIndex == $rowlen) {
$tempIndex = $tempIndex+2*$rowlen;
} else {
$tempIndex = $tempIndex+(2*($rowlen-$rowIndex));
}
$r++;
$newrow=0;
} else {

if(($rowIndex > 0 ) ) { #don't do on first row
if($newrow==0) {
@array[$tempIndex] = @letter[$r];
$r++;
$tempIndex = $tempIndex+2*$rowlen-(2*($rowlen-$rowIndex));
if ($tempIndex >$arrayLen) { $newrow =1; }
}
}

if($rowIndex != $rowlen) { #don't do on last row
if($newrow==0){
@array[$tempIndex] = @letter[$r];
$r++;
$tempIndex = $tempIndex+(2*($rowlen-$rowIndex));
if ($tempIndex > $arrayLen) { $newrow =1 ; }
}
}
}
}

for ($r=0;$r <= scalar(@letter) ;$r++){
print @array[$r];
}

print "\n";
} #end sub

#main
$rowlen = @ARGV[0];
$cryptStr = @ARGV[1];
if ( @ARGV == 0) {
print "call with ./zigzag_d.pl rowlength cryptmessage \neg. ./zigzag_d.pl 3 COPATGAHRRY\n";
#do a demo
$cryptStr="WECRLTEERDSOEEFEAOCAIVDEN";
$rowlen =3;
unzig;
} else {
#there was command line input
unzig;
}




And a few lines for a test script

./zigzag_e.pl 3 CARTOGRAPHY
./zigzag_d.pl 3 COPATGAHRRY

./zigzag_e.pl 4 THISISENCRYPTEDWITHTHEZIGZAGCYPHER
./zigzag_d.pl 4 TETHGPHSNPETTIZYHIICYDIHZACESRWEGR

./zigzag_d.pl 6 CWIHEOGEAHNDRTDULEEBIR
./zigzag_d.pl 10 CERHDYTOHEGASSVAOOEFCLWADANR

No comments: