Created
July 26, 2012 16:12
-
-
Save RoxasShadow/3182971 to your computer and use it in GitHub Desktop.
Vigènere in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## | |
## Sirius Fucking Licence 1.2 "ShitStorm" ## | |
## Do the fuck you want. Get the fuck off. ## | |
## Using this licence don't make you more trasgressive. ## | |
## And doesn't mean you're not an asshole. ## | |
##~~~~~~~~~~~~~~~*The quiet after the shitstorm*~~~~~~~~~~~~~~~~~~~## | |
## Sirius Fucking Manifesto ## | |
## With this software pubblication licence you can modify, rewrite ## | |
## rape, burn, kill, delete, fuck, do nothing. In few words: ## | |
## DO DAFUQ YOU WANT AND DON'T EXCORIATE MY BALLS ## | |
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## | |
module Vigenere | |
# The length of the clear text, cipher text and worm must be equals! | |
# For more information read http://en.wikipedia.org/wiki/Vigenère_cipher | |
@alphabeth = [*(?A..?Z)] | |
@numbers = [*([email protected])] | |
@matrix = Hash[ @alphabeth.zip(@numbers) ] | |
# Ci = (Mi + Ki) mod 26 | |
def self.encode(text, worm) | |
vigenere = '' | |
i = 0 | |
text.each_char { |c| | |
pos = @matrix[c] | |
pos_worm = @matrix[worm[i]] | |
sum = (pos + pos_worm) % 26 | |
vigenere << ((sum > @alphabeth.length) ? @alphabeth.first : @matrix.key(sum)) | |
i += 1 | |
} | |
vigenere | |
end | |
# Mi = (Ci - Ki) mod 26 | |
def self.decode(vigenere, worm) | |
text = '' | |
i = 0 | |
vigenere.each_char { |c| | |
pos = @matrix[c] | |
pos_worm = @matrix[worm[i]] | |
sum = (pos - pos_worm) % 26 | |
text << ((sum > @alphabeth.length) ? @alphabeth.first : @matrix.key(sum)) | |
i += 1 | |
} | |
text | |
end | |
end | |
puts Vigenere::encode 'ATTACKATDAWN', 'LEMONLEMONLE' | |
puts Vigenere::decode 'LXFOPVEFRNHR', 'LEMONLEMONLE' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment