如何为Perl中的凯撒密码分配字母表?

时间:2013-10-10 01:59:54

标签: string perl encryption

我编写了一个程序来加密对应于字母表字母的数字并对其进行解密,但是如何制作它以便在我要求输入时将每个字母分配给它的数字然后执行操作并打印加密和解密没有几行代码的消息?这是我的计划:

print "Caesar's Cipher\n\n";
print "Reference:\n\n";
print "A   B   C   D   E   F   G   H   I   J   K   L    M\n";
print "0   1   2   3   4   5   6   7   8   9   10  11   12\n\n";
print "N   O   P   Q   R   S   T   U   V   W   X   Y    Z\n";
print "13  14  15  16  17  18  19  20  21  22  23  24   25\n";
print "\nEnter a Message (User numbers separated by space):\n";
$string = <>; 

@sarray = split(" ",$string);

foreach $x (@sarray){
    if ($x >=0 && $x <= 25){
        $x = ($x+3)%26;
    } else {
        print "Entered incorrect message.\n"; 
        die;
    }
}
print "\nEncryption: \n";
print "@sarray\n";

foreach $x (@sarray){
    if ($x >=0 && $x <= 25){
        $x = ($x-3)%26;
    } else {
        print "Entered incorrect message.\n"; 
        die;
    }
}

print "Decryption: \n";
print "@sarray\n";

我希望能够输入类似“HELLO”的东西,然后它会加密消息并解密它。

2 个答案:

答案 0 :(得分:2)

您必须考虑大写和小写,数字,加上空格字符和标点符号。目前你只处理大写字母alpha。你需要一个将字符映射到数字的散列,以及一个映射另一种方式的散列。

$inputChar = character to be encoded
$charset = " ABCDEFGHI...Zabcdef...z0123456789!@#$%^&*...";
$code = index($charset,$char);
# encode here as in your example using length($charset) instead of 26
$outputChar = substr($charset,$code,1);

将此逻辑应用于邮件中的所有字符,以构建加密邮件。

答案 1 :(得分:1)

Jim所提供的解决方案超出了要求的范围,因为OP仅希望从A到Z的字母字符。一种更简单的实现方法是,以J为例搜索:

my @alpha = ('A'..'Z');
my $s = 'J';
my( $index ) = grep{ $alpha[ $_ ] eq $s } 0..$#alpha;