Skip to content

Instantly share code, notes, and snippets.

@RileyMills
Created November 6, 2014 17:42
Show Gist options
  • Save RileyMills/bac57c2506e91dca94f8 to your computer and use it in GitHub Desktop.
Save RileyMills/bac57c2506e91dca94f8 to your computer and use it in GitHub Desktop.
Ruby implementation of a Vigenere Cipher
class VigenereCipher
attr_reader :input
attr_reader :key
attr_reader :output
def initialize(input, key)
@input = input
@key = key.downcase.gsub(/\W|\d|_/, "")
while @key.size < @input.length
@key = @key * 2
end
@key = @key[0, @input.size]
@output = @input
tabula_recta
end
def alphabet
@alphabet ||= ('a'..'z').to_a.join
end
def upper_alphabet
@upper_alphabet ||= ('A'..'Z').to_a.join
end
def tabula_recta
@table ||= generate_table
end
def generate_table
base = ('a'..'z').to_a
rect = []
26.times do |i|
rect << base.rotate(i)
end
rect
end
def encode
output = ""
@output.each_char.with_index do |c, i|
x = alphabet.index(@key[i])
y = alphabet.index(c) || upper_alphabet.index(c)
ciphered = (y.nil? ? c : tabula_recta[x][y].dup)
ciphered.upcase! if c == c.upcase
output << ciphered
end
@output = output
end
def decode
output = ""
@output.each_char.with_index do |c, i|
x = alphabet.index(@key[i])
y = tabula_recta[x].index(c.downcase)
ciphered = (y.nil? ? c : alphabet[y].dup)
ciphered.upcase! if c == c.upcase
output << ciphered
end
@output = output
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment