65904709b86fe5f3a5ada44cb47cf86d

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?

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 !

D41d8cd98f00b204e9800998ecf8427e

bob

July 18, 2010, July 18, 2010 02:11, permalink

1 rating. Login to rate!

you know that for modulo, you can use the "%" operator, right?

65904709b86fe5f3a5ada44cb47cf86d

DoctorNo

July 18, 2010, July 18, 2010 06:52, permalink

No rating. Login to rate!

Yeah. but writing "modulo" makes it seem more clear to me. :)

A8d3f35baafdaea851914b17dae9e1fc

Adam

July 19, 2010, July 19, 2010 05:32, permalink

2 ratings. Login to rate!
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
D134a5da18b14a209b0099c720fd2e36

NullUserException

August 11, 2010, August 11, 2010 00:37, permalink

1 rating. Login to rate!

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.

Your refactoring





Format Copy from initial code

or Cancel