Refactor x2

master
E. Almqvist 3 years ago
parent 7de25c02d8
commit fdaf12ec58
  1. 33
      ma5/rsa/rsa.rb
  2. 12
      ma5/rsa/test.rb

@ -63,13 +63,17 @@ module RSA
return str return str
end end
def inspect(endchar="\n") def to_si
return @data.join " "
end
def to_s
pattern = "c" * @data.length pattern = "c" * @data.length
return "\'#{@data.pack(pattern)}\'#{endchar}" return @data.pack(pattern)
end end
def encrypt(pubkey) private def crypt(key)
e, n = pubkey e, n = key
crypt = [] crypt = []
@data.each do |c| @data.each do |c|
cr = (c ** e) % n cr = (c ** e) % n
@ -79,23 +83,20 @@ module RSA
return crypt return crypt
end end
def decrypt(privkey) def encrypt(key)
d, n = privkey self.crypt(key.pubkey)
crypt = [] end
@data.each do |c|
cr = (c ** d) % n
crypt << cr
end
return crypt def decrypt(key)
self.crypt(key.privkey)
end end
def encrypt!(pubkey) def encrypt!(key)
@data = self.encrypt(pubkey) @data = self.encrypt(key)
end end
def decrypt!(privkey) def decrypt!(key)
@data = self.decrypt(privkey) @data = self.decrypt(key)
end end
end end
end end

@ -42,11 +42,13 @@ msg = gets.chomp
data = RSA::Data.new(msg) data = RSA::Data.new(msg)
puts puts
data.encrypt!(key.pubkey) data.encrypt!(key)
puts "Encrypted bytes: #{data.raw}" puts "Encrypted bytes (hex): #{data.raw}"
puts "Encrypted bytes (dec): #{data.to_si}"
puts puts
data.decrypt!(key.privkey) data.decrypt!(key)
puts "Decrypted bytes: #{data.raw}" puts "Decrypted bytes (hex): #{data.raw}"
puts "Decrypted msg: #{data.inspect}" puts "Decrypted bytes (dec): #{data.to_si}"
puts "Decrypted msg: #{data.to_s}"

Loading…
Cancel
Save