Caesar cipher: Difference between revisions
(Caeser cipher, with key from 1 to 25.) |
(→{{header|Perl 6}}: Added Perl 6 solution) |
||
Line 3: | Line 3: | ||
Caesar cipher is identical to [[Vigenère cipher]] with key of length 1. Also, [[Rot-13]] is identical to Caesar cipher with key 13. |
Caesar cipher is identical to [[Vigenère cipher]] with key of length 1. Also, [[Rot-13]] is identical to Caesar cipher with key 13. |
||
=={{header|Perl 6}}== |
|||
<lang perl6>my @alpha = 'A' .. 'Z'; |
|||
sub encrypt ( $key where 1..25, $plaintext ) { |
|||
$plaintext.trans( @alpha Z=> @alpha.rotate($key) ); |
|||
} |
|||
sub decrypt ( $key where 1..25, $cyphertext ) { |
|||
$cyphertext.trans( @alpha.rotate($key) Z=> @alpha ); |
|||
} |
|||
my $original = 'THE FIVE BOXING WIZARDS JUMP QUICKLY'; |
|||
my $en = encrypt( 13, $original ); |
|||
my $de = decrypt( 13, $en ); |
|||
.say for $original, $en, $de; |
|||
say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );</lang> |
|||
Output:<pre>THE FIVE BOXING WIZARDS JUMP QUICKLY |
|||
GUR SVIR OBKVAT JVMNEQF WHZC DHVPXYL |
|||
THE FIVE BOXING WIZARDS JUMP QUICKLY |
|||
OK</pre> |
Revision as of 03:20, 12 June 2011
Implement a Caesar cipher, both encryption and decryption. The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z). The encryption replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "monoalphabetic substitution cipher" provides almost no security, because an attacker who has the encrypted message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13.
Perl 6
<lang perl6>my @alpha = 'A' .. 'Z'; sub encrypt ( $key where 1..25, $plaintext ) {
$plaintext.trans( @alpha Z=> @alpha.rotate($key) );
} sub decrypt ( $key where 1..25, $cyphertext ) {
$cyphertext.trans( @alpha.rotate($key) Z=> @alpha );
}
my $original = 'THE FIVE BOXING WIZARDS JUMP QUICKLY'; my $en = encrypt( 13, $original ); my $de = decrypt( 13, $en );
.say for $original, $en, $de;
say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );</lang>
Output:
THE FIVE BOXING WIZARDS JUMP QUICKLY GUR SVIR OBKVAT JVMNEQF WHZC DHVPXYL THE FIVE BOXING WIZARDS JUMP QUICKLY OK