Recently i have started to learn ruby
because it's the core language for the rails framework.
Here the cipher engine which uses the old caesar cipher algorithm,
i have used file concepts to read and write the both
encrypted and decrypted outputs to files.
We can also use other methods separately,
launch your irb then
load 'encryptor.rb'
make an instance of the Encryptor class by
e = Encryptor.new
to check all the available methods
e.methods
Here is the source
Here the cipher engine which uses the old caesar cipher algorithm,
i have used file concepts to read and write the both
encrypted and decrypted outputs to files.
We can also use other methods separately,
launch your irb then
load 'encryptor.rb'
make an instance of the Encryptor class by
e = Encryptor.new
to check all the available methods
e.methods
Here is the source
class Encryptor def cipher(rotation) chars = (' '..'z').to_a rotated_chars = chars.rotate(rotation) Hash[chars.zip(rotated_chars)] end def encrypt_letter(char,rotation) cipher_for_rotate = cipher(rotation) cipher_for_rotate[char] end def decrypt_letter(char,rotation) decypher_rotate = cipher(-rotation) decypher_rotate[char] end #encryption method def encrypt(string,rotation) #split the string to letters letters = string.split("") #encrypt each letters and store it in array result = letters.collect do |letter| enc_char = encrypt_letter(letter,rotation) end #join the characters result.join end #encrypt a file def encrypt_file(filename,rotation) #1. create the file handle to the input file f = File.open(filename, "r") #2. read the text of the input file text = f.read #3 encrypt the text encrypted = encrypt(text,rotation) #4 create a name for output file output = "#{filename}.encrypted" #5. create an output file handle out = File.open(output,"w") #6. write out the text out.write(encrypted) #7. close the file f.close out.close end def decrypt(string,rotation) #split the string to letters letters = string.split("") #decrypt each letters result = letters.collect do |letter| dec_char = decrypt_letter(letter,rotation) end #join result.join end def decrypt_file(filename,rotation) #create filehandler to read f = File.open(filename,"r") #read the cipher cipher = f.read #decrypt the cipher decrypted_msg = decrypt(cipher,rotation) #output filename output_filename = filename.gsub("encrypted","decrypted") #file handler to write out = File.open(output_filename,"w") #write contents out.write(decrypted_msg) #close out.close end end
Comments
Post a Comment