Time for an 2014 update…

This commit is contained in:
Ingy döt Net 2014-01-17 05:32:22 +00:00
parent 372c577f83
commit 09687c4926
2520 changed files with 34227 additions and 7318 deletions

View file

@ -1,34 +1,23 @@
class VigenereCipher
module VigenereCipher
BASE = 'A'.ord
SIZE = 'Z'.ord - BASE + 1
def key=(key)
@key = key.upcase.gsub(/[^A-Z]/, '')
def encrypt(text, key)
crypt(text, key, :+)
end
def initialize(key)
self.key= key
def decrypt(text, key)
crypt(text, key, :-)
end
def encrypt(text)
crypt(text, :+)
end
def decrypt(text)
crypt(text, :-)
end
def crypt(text, dir)
plaintext = text.upcase.gsub(/[^A-Z]/, '')
key_iterator = @key.chars.cycle
ciphertext = ''
plaintext.each_char do |plain_char|
offset = key_iterator.next.ord - BASE
ciphertext +=
((plain_char.ord - BASE).send(dir, offset) % SIZE + BASE).chr
def crypt(text, key, dir)
text = text.upcase.gsub(/[^A-Z]/, '')
key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| c.ord - BASE}.cycle
text.each_char.inject('') do |ciphertext, char|
offset = key_iterator.next
ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr
end
return ciphertext
end
end

View file

@ -1,7 +1,10 @@
vc = VigenereCipher.new('Vigenere cipher')
include VigenereCipher
plaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'
ciphertext = vc.encrypt(plaintext)
recovered = vc.decrypt(ciphertext)
key = 'Vigenere cipher'
ciphertext = VigenereCipher.encrypt(plaintext, key)
recovered = VigenereCipher.decrypt(ciphertext, key)
puts "Original: #{plaintext}"
puts "Encrypted: #{ciphertext}"
puts "Decrypted: #{recovered}"