Skip to content

Instantly share code, notes, and snippets.

@ianhenrysmith
Created July 27, 2015 12:43
Show Gist options
  • Select an option

  • Save ianhenrysmith/865ae1db00631eff430b to your computer and use it in GitHub Desktop.

Select an option

Save ianhenrysmith/865ae1db00631eff430b to your computer and use it in GitHub Desktop.
class Crypto
attr_reader :key, :length, :output
AZ_INT_MAPPINGS = {"a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5, "f"=>6, "g"=>7, "h"=>8, "i"=>9, "j"=>10, "k"=>11, "l"=>12, "m"=>13, "n"=>14, "o"=>15, "p"=>16, "q"=>17, "r"=>18, "s"=>19, "t"=>20, "u"=>21, "v"=>22, "w"=>23, "x"=>24, "y"=>25, "z"=>26}
def initialize(count)
@length = count
@key = generate_key
end
def encrypt(input)
input = sanitize(input)
result = ""
(0..(input.length - 1)).each do |index|
c = input[index]
factor = key[index]
next unless factor
sum = to_int(c) + to_int(factor)
sum -= 26 if (sum > 26)
result << to_c(sum)
end
@output = result
end
def decrypt(encrypted)
result = ""
current = 0
(0..(encrypted.length - 1)).each do |index|
factor = key[index]
c = encrypted[index]
sum = to_int(c) - to_int(factor)
sum += 26 if (sum < 1)
result << to_c(sum)
end
result
end
private
def sanitize(i)
i.downcase.split("").to_a.select{ |i| characters.include?(i) }.join("")
end
def to_int(c)
AZ_INT_MAPPINGS[c]
end
def to_c(i)
int_az_mappings[i]
end
def int_az_mappings
AZ_INT_MAPPINGS.invert
end
def characters
("a".."z").to_a
end
def generate_key
result = []
(0..length).each do |c|
result << int_az_mappings[rand(26) + 1]
end
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment