puts "Please enter the sentence to be encrypted: "
plaintext = gets.chomp.upcase!
puts "Please enter the vigenere key: "
key = gets.chomp.upcase.scan(/\w/)
shift = key.collect do
|l|
l.ord - 65
end
length = shift.length
puts "The sentence to be encrypted is \"#{plaintext}\" and the vigenere key is \"#{key.join}\""
proc = plaintext.strip.gsub(/\s+/, '').scan(/\w{1,#{length}}/)
counter = 0
ciperText1 = proc.collect do |group|
test = []
group.scan(/\w/) do |letter|
test << ((letter.ord + shift[counter.modulo(length)] - 'A'.ord).modulo(26) + 65).chr
counter += 1
end
test.join
end
puts ciperText1.join
Refactorings
No refactoring yet !
bob
July 18, 2010, July 18, 2010 02:11, permalink
you know that for modulo, you can use the "%" operator, right?
DoctorNo
July 18, 2010, July 18, 2010 06:52, permalink
Yeah. but writing "modulo" makes it seem more clear to me. :)
Adam
July 19, 2010, July 19, 2010 05:32, permalink
require 'rubygems'
require 'active_support/core_ext/object/blank'
class VigenereCipher
attr_reader :text, :key
def initialize(text, key)
@text, @key = clean(text), clean(key)
raise(ArgumentError, "text may not be blank.") if @text.blank?
raise(ArgumentError, "key may not be blank.") if @key.blank?
end
def encrypt
key_enumerator = (key * (text.size / key.size).ceil).each_byte
text.each_byte.map { |byte| (((byte + key_enumerator.next) % 26) + 65).chr }.join
end
private
def clean(string)
string.upcase.gsub(/[^A-Z]/, '')
end
end
if __FILE__ == $0
print "Please enter the sentence to be encrypted: "
text = gets.chomp!
print "Please enter the vigenere key: "
key = gets.chomp!
vigenere_cipher = VigenereCipher.new(text, key)
puts "The sentence to be encrypted is \"#{vigenere_cipher.text}\" and the vigenere key is \"#{vigenere_cipher.key}\""
puts vigenere_cipher.encrypt
end
NullUserException
August 11, 2010, August 11, 2010 00:37, permalink
When it comes to reinventing the wheel, Encryption is one area where this could be very very dangerous. The Vignere cypher is broken, anything built on it will, very likely, be broken as well. Anyone with some knowledge in encryption will not even consider such a thing.
You should really use a battle-tested solution like AES.
I tried implementing this basic vigenere cipher.
I actually want to use it as a step in my bigger text encryption system.
i wanna know if i'll benefit by making it a method itself, and whether it can be improved?