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> |
<lang Ruby>module VigenereCipher |
||
BASE = 'A'.ord |
BASE = 'A'.ord |
||
SIZE = 'Z'.ord - BASE + 1 |
SIZE = 'Z'.ord - BASE + 1 |
||
def |
def encrypt(text, key) |
||
crypt(text, key, :+) |
|||
end |
end |
||
def |
def decrypt(text, key) |
||
crypt(text, key, :-) |
|||
end |
end |
||
def |
def crypt(text, key, dir) |
||
text = text.upcase.gsub(/[^A-Z]/, '') |
|||
⚫ | |||
end |
|||
text.each_char.inject('') do |ciphertext, char| |
|||
⚫ | |||
def decrypt(text) |
|||
⚫ | |||
crypt(text, :-) |
|||
end |
|||
def crypt(text, dir) |
|||
plaintext = text.upcase.gsub(/[^A-Z]/, '') |
|||
⚫ | |||
ciphertext = '' |
|||
plaintext.each_char do |plain_char| |
|||
⚫ | |||
ciphertext += |
|||
⚫ | |||
end |
end |
||
return ciphertext |
|||
end |
end |
||
Line 2,242: | Line 2,231: | ||
Demonstration: |
Demonstration: |
||
<lang Ruby> |
<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 = |
ciphertext = VigenereCipher.encrypt(plaintext, key) |
||
recovered = |
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> |
|||
Original: Beware the Jabberwock, my son! The jaws that bite, the claws that catch! |
|||
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY |
Encrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY |
||
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH |
Decrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH |
||
</pre> |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |