/frequency_analysis.rb Secret
Last active
October 20, 2016 19:48
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ciphertexts = [ | |
"VGYURYPEDFNCEPGEWELLPVNWRDCNFGMGXQEPPRG-CBFIGLEMG", | |
"EQ’PMEIGQNVBAGBTFEGMSYNRKMNWEPBLWBYPSNWMQNFBDWEQVYNR-CBFIGLEMG" | |
] | |
english_freqs = "ETAOINSHRDLCUMWFGYPBVKJXQZ".chars | |
# count letter frequencies in ciphertexts | |
char_freqs = Hash.new(0) | |
(ciphertexts.join).each_char {|c| char_freqs[c] += 1} | |
# sort by letter frequency freqs (descending) | |
ciphertext_freqs = Hash[char_freqs.sort_by{|k,v| -v}] | |
# remove non-alphanumeric ciphertext chars (e.g. punctuation) | |
(ciphertext_freqs.keys - english_freqs).each {|p| ciphertext_freqs.delete(p)} | |
# display the letter and frequency mappings | |
puts "Ciphertext => English (count)" | |
ciphertext_freqs.each_with_index do |ct_freq,index| | |
puts "#{ct_freq.first} => #{english_freqs[index]} (#{ct_freq.last})" | |
end | |
used_english_freqs = english_freqs[0..ciphertext_freqs.count-1].join | |
cipher_char_freqs = ciphertext_freqs.keys.join | |
ciphertexts.each do |ciphertext| | |
ciphertext_before = ciphertext | |
ciphertext_after = ciphertext.tr(cipher_char_freqs, used_english_freqs) | |
puts "Ciphertext before: #{ciphertext_before}" | |
puts "Ciphertext after: #{ciphertext_after}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment