module RSA def self.n_inv(a, m) (1..m).each{|x| break x if (a*x % m == 1)} end class Key def initialize(p1, p2) puts "Generating key pair..." @n = p1 * p2 @phi = (p1-1)*(p2-1) enc = [] (2...@phi).each do |e| dom = e.gcd(@phi) if dom == 1 then enc << e end end @e = enc.sample p enc @d = RSA.n_inv(@e, @n) puts "e=#{@e} d=#{@d}" end def pubkey return @e, @n end def privkey return @d, @n end end class Data attr_reader :data def initialize(data) @data = data if data.is_a? String then @data = @data.split("").map do |c| c.ord.to_i end end puts "Generated bytearray: #{@data}" end def raw str = "" @data.each do |byte| str += "\\x#{byte.to_s 16}" end return str end def inspect(endchar="\n") pattern = "c" * @data.length return "# \'#{@data.pack(pattern)}\'#{endchar}" end def encrypt(pubkey) e, n = pubkey crypt = [] @data.each do |c| cr = (c ** e) % n crypt << cr end return crypt end def decrypt(privkey) d, n = privkey crypt = [] @data.each do |c| cr = (c ** d) % n crypt << cr end return crypt end def encrypt!(pubkey) @data = self.encrypt(pubkey) end def decrypt!(privkey) @data = self.decrypt(privkey) end end end