Vigenère cipher: Difference between revisions

(Updated second D entry)
Line 2,205:
 
=={{header|Ruby}}==
<lang Ruby>classmodule VigenereCipher
 
BASE = 'A'.ord
SIZE = 'Z'.ord - BASE + 1
 
def key=encrypt(text, key)
@key =crypt(text, key.upcase.gsub(/[^A-Z]/, '':+)
end
 
def initializedecrypt(text, key)
self.key=crypt(text, key, :-)
end
 
def encryptcrypt(text, key, dir)
crypt(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.ord - BASE
def decrypt(text)
ciphertext << ((plain_charchar.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
return ciphertext
end
Line 2,242 ⟶ 2,231:
Demonstration:
 
<lang Ruby>vc =include VigenereCipher.new('Vigenere cipher')
 
plaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'
key = 'Vigenere cipher'
ciphertext = vcVigenereCipher.encrypt(plaintext, key)
recovered = vcVigenereCipher.decrypt(ciphertext, key)
 
puts "Original: #{plaintext}"
puts "Encrypted: #{ciphertext}"
puts "Decrypted: #{recovered}"</lang>
 
{{out}}
Output:
<pre>
 
<pre>Original: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH</pre>
</pre>
 
=={{header|Rust}}==
Anonymous user