master
E. Almqvist 3 years ago
parent adfa2eb253
commit bdc1bd17dc
  1. 55
      ma5/rsa/rsa.rb

@ -5,46 +5,61 @@ module RSA
class Key class Key
def initialize(p1, p2) def initialize(p1, p2)
@p1 = p1 puts "Generating key pair..."
@p2 = p2
@n = p1 * p2 @n = p1 * p2
@phi = (p1-1)*(p2-1) @phi = (p1-1)*(p2-1)
(2...@phi).each do |e| (2...@phi).each do |e|
if( e.gcd(@phi) == 1 ) then dom = e.gcd(@phi)
if dom == 1 then
@e = e @e = e
break break
end end
end end
@d = RSA.mod_inv(@e, @phi) @d = RSA.mod_inv(@e, @n)
end end
def pubkey def pubkey
return @e, @phi return @e, @n
end end
def privkey def privkey
return @d, @phi return @d, @n
end end
end end
def self.encrypt(text, key) class Data < Array
n, mod = key.pubkey attr_reader :data
p [n, mod] def initialize(data)
text_enc = "" super data
text.split("").each_with_index do |c, i| if data.class == String then
charint = c.ord ** n self = data.split("")
p charint self = self.map do |c|
charint %= mod c.to_i
p charint end
puts "enc #{c.ord} -> #{charint}" end
text_enc += charint.chr
end end
return text_enc def inspect
end self.join " "
end
def self.decrypt(text) def encrypt(key)
e, mod = key.pubkey
crypt = []
text.split("").each_with_index do |c, i|
c = c.ord ** e
c %= mod
crypt << charint
end
return crypt
end
def encrypt!(key)
self = self.encrypt(key)
end
end end
end end

Loading…
Cancel
Save