master
E. Almqvist 3 years ago
parent adfa2eb253
commit bdc1bd17dc
  1. 51
      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
class Data < Array
attr_reader :data
def initialize(data)
super data
if data.class == String then
self = data.split("")
self = self.map do |c|
c.to_i
end end
end end
end
def inspect
self.join " "
end
def self.encrypt(text, key) def encrypt(key)
n, mod = key.pubkey e, mod = key.pubkey
p [n, mod] crypt = []
text_enc = ""
text.split("").each_with_index do |c, i| text.split("").each_with_index do |c, i|
charint = c.ord ** n c = c.ord ** e
p charint c %= mod
charint %= mod crypt << charint
p charint
puts "enc #{c.ord} -> #{charint}"
text_enc += charint.chr
end end
return text_enc return crypt
end end
def self.decrypt(text) def encrypt!(key)
self = self.encrypt(key)
end
end end
end end

Loading…
Cancel
Save