【问题标题】:How to assign letters of alphabet to numbers for Caesar cipher in Perl?如何在Perl中将字母分配给凯撒密码的数字?
【发布时间】:2013-10-17 15:01:30
【问题描述】:

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

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”之类的内容,然后它会对消息进行加密和解密。

【问题讨论】:

    标签: string perl encryption


    【解决方案1】:

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

    $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);
    

    将此逻辑应用于消息中的所有字符以构建加密消息。

    【讨论】:

      【解决方案2】:

      上述 Jim 提供的解决方案超出了所要求的范围,因为 OP 只需要从 A 到 Z 的字母字符。实现这一点的更简单方法是以 J 为例进行搜索:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-02
        • 1970-01-01
        相关资源
        最近更新 更多