Secret codes
Julius Caesar is said to have written his secret letters by shifting every letter three places along the alphabet: A became D, B became E. To build that you need one fact – for the computer every character is a number (lesson 20 showed it). ord gives a character's number, chr turns a number back into a character:
p "A".ord
p "a".ord
p 98.chr
"bacon".chars.map { |c| c.ord }So shifting a letter is plain arithmetic: number plus 3, back to a character. A whole word goes letter by letter with chars, map and join:
word = "bacon"
word.chars.map { |c| (c.ord + 3).chr }.joinBut at the end of the alphabet it breaks: "z".ord + 3 is the number of }, not of a letter. The alphabet has to wrap round, z → c. The remainder % from lesson 2 does that: count from a (0 to 25), add the key, take the remainder of 26, add a back on. Anything that isn't a small letter stays as it is:
def shift_letter(letter, key)
return letter unless ("a".."z").include?(letter)
((letter.ord - "a".ord + key) % 26 + "a".ord).chr
end
p shift_letter("z", 3)
p shift_letter("!", 3)
"chunky bacon!".chars.map { |c| shift_letter(c, 3) }.joinDecoding is shifting back – a negative key. And with key 13, called ROT13, encoding and decoding are the same thing, because 13 + 13 = 26: twice round brings every letter home.
secret = "chunky bacon!".chars.map { |c| shift_letter(c, 3) }.join
p secret
p secret.chars.map { |c| shift_letter(c, -3) }.join
rot = "hello".chars.map { |c| shift_letter(c, 13) }.join
p rot
rot.chars.map { |c| shift_letter(c, 13) }.joinRuby even has a shortcut for swapping characters: tr (“translate”) replaces every character of the first list by the one at the same place in the second. ROT13 in one line:
"chunky bacon".tr("a-z", "n-za-m")How do you crack a Caesar code without knowing the key? There are only 25 keys – just try them all! A computer does that in no time; you only have to spot the line that makes sense:
mystery = "eqfg ku hwp"
1.upto(25) do |key|
guess = mystery.chars.map { |c| shift_letter(c, -key) }.join
puts "#{key}: #{guess}"
endThat is why Caesar's code is a toy today. The lock in your browser's address bar uses keys so long that trying them all would take far longer than the universe has existed – but the idea, a rule plus a secret key, is the same.
caesar(text, key) that shifts every small letter of text by key and leaves everything else alone: caesar("hello, fox!", 1) gives "ifmmp, gpy!", and a negative key decodes. shift_letter from above can do the work for a single letter.# def caesar(text, key)
# ... # every letter shifted by key, everything else stays
# end
# caesar("hello, fox!", 1)
key (1 to 25) under which the decoded message contains "bacon" – let Ruby search with find – and put the decoded message into plain.intercepted = "esp qzi pled mlnzy"
# key = ... # the key under which the message contains "bacon"
# plain = ... # the message, decoded with that key