Advertisement
sleksey

brute force Caesar Cipher Perl

Apr 2nd, 2023
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.61 KB | Cybersecurity | 0 0
  1. #!/usr/bin/perl
  2.  
  3. #brute force Caesar Cipher.
  4. #The script uses a score based system, The score is incremented based on the frequency of the shifted character in the English language and an additional score is given to vowels, the highest score is the returned string which is most likely to be decrypted.
  5.  
  6. #pretty simple
  7.  
  8. use strict;  
  9. use warnings;
  10.  
  11. my $cipher_text = "ozxy fstymjw ujwq lnwq";
  12. my $decoded_text = brute_force_caesar($cipher_text);
  13. print "Decoded text: $decoded_text\n";
  14.  
  15. sub brute_force_caesar {
  16.     my ($encrypted_text) = @_;
  17.     my $decrypted_text;
  18.     my $max_score = 0;
  19.     my $vowel_score = 0.5;
  20.     my $shift;
  21.     my %letter_freq = (
  22.         a => 8.12, b => 1.49, c => 2.71, d => 4.32, e => 12.02,
  23.         f => 2.3, g => 2.03, h => 5.92, i => 7.31, j => 0.1,
  24.         k => 0.69, l => 3.98, m => 2.61, n => 6.95, o => 7.68,
  25.         p => 1.82, q => 0.11, r => 6.02, s => 6.28, t => 9.1,
  26.         u => 2.88, v => 1.11, w => 2.09, x => 0.17, y => 2.11, z => 0.07
  27.     );
  28.    
  29. for $shift (0..25) {
  30.     my ($score, $shifted_text) = (0, "");
  31.     for my $char (split //, $encrypted_text) {
  32.         if ($char =~ /[a-z]/i) {
  33.             my $shifted_char = chr(((ord(lc $char) - 97 + $shift) % 26) + 97);
  34.             $shifted_text .= $char =~ /[a-z]/ ? $shifted_char : uc $shifted_char;
  35.             $score += ($letter_freq{lc $shifted_char} // 0) + ($vowel_score * ($shifted_char =~ /[aeiou]/));
  36.         } else {
  37.             $shifted_text .= $char;
  38.         }
  39.     }
  40.    
  41.    
  42.     ($max_score, $decrypted_text) = ($score, $shifted_text) if $score > $max_score;
  43.  
  44. }
  45.    
  46.     return $decrypted_text;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement