Skip to content

Instantly share code, notes, and snippets.

@annawinkler
Created March 14, 2014 04:43
Show Gist options
  • Save annawinkler/9542257 to your computer and use it in GitHub Desktop.
Save annawinkler/9542257 to your computer and use it in GitHub Desktop.
#
# This file demonstrates a Caesar cipher
# There is an encrypt function for encoding plaintext into ciphertext
# and a decrypt function for converting ciphertext into plaintext
#
# given plaintext and key, return encoded ciphertext
def encrypt(plaintext, key, letters)
plaintext_as_numbers = []
# Represent each plaintext letter as a corresponding number
# for example a=>0, b=>1, ... y=>25, z=>26, '<space>'=>27
plaintext.downcase.each_char do |l|
plaintext_as_numbers << letters.index(l)
end
# Encryption - Caesar cipher shift
# Add the key to each number and mod by the length of the letters
# - or 27
encrypted = []
plaintext_as_numbers.each do |n|
encrypted << ((n+key) % letters.length)
end
# convert the shifted/encrypted numbers back to letters
ciphertext = ""
encrypted.each do |n|
ciphertext << letters[n]
end
ciphertext
end
# given ciphertext and key, return decoded plaintext
def decrypt(ciphertext, key, letters)
# Represent each plaintext letter as a corresponding number
# for example a=>0, b=>1, ... y=>25, z=>26, '<space>'=>27
ciphertext_as_numbers = []
ciphertext.downcase.each_char do |l|
ciphertext_as_numbers << letters.index(l)
end
# encryption... Caesar cipher shift
# add the key to each number and mod by 27
decrypted = []
ciphertext_as_numbers.each do |n|
decrypted << ((n-key) % letters.length)
end
# convert the shifted/encrypted numbers back to letters
plaintext = ""
decrypted.each do |n|
plaintext << letters[n]
end
plaintext
end
# This is the message to encode
plaintext = "hello world"
# This is the secret key used for encoding the Caesar cipher
key = 4
letters = "abcdefghijklmnopqrstuvwxyz "
ciphertext = encrypt(plaintext, key, letters)
puts "Ciphertext = #{ciphertext}"
puts "Decrypted = #{decrypt(ciphertext, key, letters)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment