Skip to content

Instantly share code, notes, and snippets.

@SamMeeDee
Last active April 28, 2017 01:28
Show Gist options
  • Save SamMeeDee/51b7adfbb841de19512ea9ecd6d8f596 to your computer and use it in GitHub Desktop.
Save SamMeeDee/51b7adfbb841de19512ea9ecd6d8f596 to your computer and use it in GitHub Desktop.
A class containing methods that can be used to run additive and subtractive one-time pad operations, both on characters and strings.
# These methods are all class methods. To convert to instance methods, remove the "self." portion of the method names.
# In order to decrypt, utilize the opposite method you used to encrypt, and pass the method the encrypted text, followed by the key.
# You can use these methods to determine the key used to encrypt if you have both the plain text and ciphertext.
# - If an additive method was used to encrypt, call the subtractive method, passing in the ciphertext, followed by the plaintext
# - If a subtractive method was used to encrypt, call the subtractive method, passing in the plaintext, followed by the ciphertext
class OneTimePad
def self.to_num(a)
index = ('a'..'z').to_a
return index.index(a) + 1
end
def self.to_alpha(i)
index = ('a'..'z').to_a
return index[i-1]
end
def self.char_add(p,k)
plain = to_num(p)
key = to_num(k)
cipher = plain + key
cipher %= 26
return to_alpha(cipher)
end
def self.char_sub(p,k)
plain = to_num(p)
key = to_num(k)
cipher = plain - key
cipher %= 26
return to_alpha(cipher)
end
def self.string_add(plain,key)
plain = plain.chars
key = key.chars
cipher = ""
plain.zip(key).each do |p,k|
cipher += char_add(p,k)
end
return cipher
end
def self.string_sub(plain,key)
plain = plain.chars
key = key.chars
cipher = ""
plain.zip(key).each do |p,k|
cipher += char_sub(p,k)
end
return cipher
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment