Hello,
I am trying to encrypt a string using a predetermined encryption map. I know that this a very very weak form of encryption, yet that is not the real problem. I think that this working code is too long and ugly to be efficient. Can anyone suggest a way to reduce the lines of code and also make the code more efficient?
Thanks
jcr
===========================================================
sub encrypt {
my ($self, $STRING) = @_;
my $ENCRYPTED_STRING = '';
my $LENGTH = length($STRING);
my @STRING = split(//,$STRING);
my $ENCRYPTION_MAP = "abcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyz0123456789.&@=";
my @ENCRYPTION_ARRAY = split(//,$ENCRYPTION_MAP);
my $MAP_LENGTH = length($ENCRYPTION_MAP);
my $MAP_HALF = length($ENCRYPTION_MAP)/2;
for ($i=0; $i < $LENGTH; $i++) {
my $CHARACTER = $STRING
$i;
my $POSITION = index($ENCRYPTION_MAP, "$CHARACTER");
if ($POSITION < 0) {
$ENCRYPTED_STRING .= &EscapeCharacter("$CHARACTER");
}
else {
$ENCRYPTED_STRING .= &EscapeCharacter("$ENCRYPTION_ARRAY
($POSITION + $MAP_HALF) % $MAP_LENGTH");
}
}
return $ENCRYPTED_STRING;
}
##################################
# CHARACTER ESCAPING SUBROUTINE: #
##################################
sub EscapeCharacter {
my $CHARACTER_TO_ESCAPE = shift;
if (($CHARACTER_TO_ESCAPE eq '&')
|| ($CHARACTER_TO_ESCAPE eq '\\')
|| ($CHARACTER_TO_ESCAPE eq ' ')
|| ($CHARACTER_TO_ESCAPE eq '%')
|| ($CHARACTER_TO_ESCAPE eq '@')
|| ($CHARACTER_TO_ESCAPE eq '/')
|| ($CHARACTER_TO_ESCAPE eq '#')
|| ($CHARACTER_TO_ESCAPE eq '=')
|| ($CHARACTER_TO_ESCAPE eq '"')
|| ($CHARACTER_TO_ESCAPE eq "'")
|| ($CHARACTER_TO_ESCAPE eq '+')
|| ($CHARACTER_TO_ESCAPE eq '|')
|| ($CHARACTER_TO_ESCAPE eq '?')){
$CHARACTER_TO_ESCAPE = ord("$CHARACTER_TO_ESCAPE");
$CHARACTER_TO_ESCAPE = sprintf "%x", $CHARACTER_TO_ESCAPE;
return ".$CHARACTER_TO_ESCAPE";
}
else {return $CHARACTER_TO_ESCAPE;}
}
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.