Algoritmo de cesar em ruby

July 9th, 2009 by Global Leave a reply »

Estou aprendendo ruby e criptografia e resolvi implementar alguns algoritmos que estou vendo no curso de pós-graduação em criptografia. Como estou aprendendo Ruby, algumas construções podem sair pouco elegantes por não conhecer toda a API. Com o tempo as coisas melhoram.

Abaixo veja o código do algoritmo de César, seguindo os passos para substituição monoalfabética.

#!/usr/bin/ruby1.9
 
 
# Cesar crypt and decrypt algorithms
# 
# by Anderson Goulart <global@codekab.com>
# on Sat, 04 Jul 2009 20:17:03 -0300
 
$alphabet = { "a" => 0, "b" => 1, "c" => 2,
	 		  "d" => 3, "e" => 4, "f" => 5,
  		  	  "g" => 6, "h" => 7, "i" => 8,
			  "j" => 9, "k" => 10, "l" => 11,
			  "m" => 12, "n" => 13, "o" => 14,
		 	  "p" => 15, "q" => 16, "r" => 17,
			  "s" => 18, "t" => 19, "u" => 20,
			  "v" => 21, "w" => 22, "x" => 23,
			  "y" =>  24, "z" => 25 }
 
def crypt(text, key)
 
	cipher = Array.new()
 
	for i in 0..text.length-1
		cipher[i] = $alphabet.key(($alphabet[text[i]] + key)%26)
	end
 
	return cipher
end
 
def decrypt(text, key)
 
	original = Array.new()
	for i in 0..text.length-1
		original[i] = $alphabet.key(($alphabet[text[i]] - key + 26)%26)
	end
 
	return original
 
end
 
 
# main program
 
# choose your own values below
$t = "cryptography is cool"
$key = 23
 
# removes white spaces
$text = $t.gsub(/ /,'')
 
# prints the result
puts "Original text:  " + $text + "\n"
 
$cipher = crypt($text, $key).join
puts "Cipher text:    #$cipher \n"
 
$original = decrypt($cipher, $key).join
puts "Decrypted text: #$original"
Advertisement

Leave a Reply