- 论坛徽章:
- 0
|
本帖最后由 picbhan 于 2013-06-19 17:07 编辑
因为I和J无法区分,X无法确定是重复还是真实的X,且第6和第7条找到的两个字符不确定顺序,因此个人认为解密无法正确得到原来的字符串,下面是加密的程序。- #!/usr/bin/env perl
- use strict;
- use warnings;
- my $code = 'playfair example';
- my %used;
- my @matrix;
- $code =~ y/A-Z/a-z/;
- $code =~ s/\s+//g;
- $code =~ s/j/i/ig;
- my @code = split //, $code;
- for (@code) {
- next if exists $used{$_};
- $used{$_} = 1;
- push @matrix, $_;
- }
- for (97 .. 105, 107 .. 122) {
- next if exists $used{chr($_)};
- push @matrix, chr($_);
- }
- my %position;
- for my $i (0 .. 4) {
- for my $j (0 .. 4) {
- $position{$matrix[$i * 5 + $j]} = [$i, $j];
- }
- }
- my $string = 'Hide the gold in the tree stump';
- $string =~ y/A-Z/a-z/;
- $string =~ s/\s+//g;
- $string =~ s/j/i/ig;
- my @string = split //, $string;
- my @results;
- my ($k1, $k2);
- while (@string) {
- $k1 = shift @string;
- if (@string) {
- $k2 = shift @string;
- if ($k1 eq $k2) {
- unshift @string, $k1;
- $k2 = 'x';
- }
- }
- else { $k2 = 'x'; }
-
- my @idx1 = @{$position{$k1}};
- my @idx2 = @{$position{$k2}};
-
- if ($idx1[0] == $idx2[0]) { # same row
- print $matrix[$idx1[0] * 5 + ($idx1[1] + 1) % 5], $matrix[$idx2[0] * 5 + ($idx2[1] + 1) % 5], ' ';
- }
- elsif ($idx1[1] == $idx2[1]) { # same column
- print $matrix[(($idx1[0] + 1) % 5) * 5 + $idx1[1]], $matrix[(($idx2[0] + 1) % 5) * 5 + $idx2[1]], ' ';
- }
- else {
- print $matrix[$idx1[0] * 5 + $idx2[1]], $matrix[$idx2[0] * 5 + $idx1[1]], ' ';
- }
- }
复制代码 |
|