Before I begin please let me state that I am doing this for learning purposes, and am well aware of the weakness of XOR encryption.
That said, I am having a hell of a time getting a simple XOR routine to work. Here is the code that I have written so far:
#!/usr/bin/perl
use strict;
if(@ARGV < 3) {
print "Usage: $0 <key> <input file> <output file>\n";
exit(0);
}
my $key = $ARGV[0];
open(IN, $ARGV[1]) or die "Can't open infile";
open(OUT, ">$ARGV[2]") or die "Can't open outfile";
my $kp = 0;
while(<IN>) {
for my $i (0..length($_)) {
if($kp > length($key)) {
$kp = 0;
}
my $kc = substr($key, $kp++, 1);
my $char = substr($_, $i, 1);
$char ^= $kc;
print OUT $char;
}
}
close(IN);
close(OUT);
Seems simple enough, but when I encrypt a file and then attempt to de-crypt it with the same key *some* of the file decrypts correctly, but most of it is garbage. A realativly simple task in C, this has had me beating my head against a wall for some time. I'm not exactly a perl kung-fu master, so if anyone has any insight as to what I might be doing wrong, I'd greatly appreciate hearing it.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.