Vigenère cipher: Difference between revisions

Content added Content deleted
(Updated second D entry)
Line 2,205: Line 2,205:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang Ruby>class VigenereCipher
<lang Ruby>module VigenereCipher

BASE = 'A'.ord
BASE = 'A'.ord
SIZE = 'Z'.ord - BASE + 1
SIZE = 'Z'.ord - BASE + 1

def key=(key)
def encrypt(text, key)
@key = key.upcase.gsub(/[^A-Z]/, '')
crypt(text, key, :+)
end
end

def initialize(key)
def decrypt(text, key)
self.key= key
crypt(text, key, :-)
end
end

def encrypt(text)
def crypt(text, key, dir)
crypt(text, :+)
text = text.upcase.gsub(/[^A-Z]/, '')
key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| c.ord - BASE}.cycle
end
text.each_char.inject('') do |ciphertext, char|

offset = key_iterator.next
def decrypt(text)
ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr
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
end
end
return ciphertext
end
end
Line 2,242: Line 2,231:
Demonstration:
Demonstration:


<lang Ruby>vc = VigenereCipher.new('Vigenere cipher')
<lang Ruby>include VigenereCipher

plaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'
plaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'
key = 'Vigenere cipher'
ciphertext = vc.encrypt(plaintext)
ciphertext = VigenereCipher.encrypt(plaintext, key)
recovered = vc.decrypt(ciphertext)
recovered = VigenereCipher.decrypt(ciphertext, key)

puts "Original: #{plaintext}"
puts "Original: #{plaintext}"
puts "Encrypted: #{ciphertext}"
puts "Encrypted: #{ciphertext}"
puts "Decrypted: #{recovered}"</lang>
puts "Decrypted: #{recovered}"</lang>


{{out}}
Output:
<pre>

<pre>Original: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Original: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
</pre>


=={{header|Rust}}==
=={{header|Rust}}==