diff --git a/ma5/rsa/brute.rb b/ma5/rsa/brute.rb old mode 100755 new mode 100644 diff --git a/ma5/rsa/rsa.rb b/ma5/rsa/rsa.rb index ece40c5..8dd2715 100644 --- a/ma5/rsa/rsa.rb +++ b/ma5/rsa/rsa.rb @@ -1,5 +1,5 @@ module RSA - def self.mod_inv(a, m) + def self.n_inv(a, m) (1..m).each{|x| break x if (a*x % m == 1)} end @@ -9,16 +9,18 @@ module RSA @n = p1 * p2 @phi = (p1-1)*(p2-1) + enc = [] (2...@phi).each do |e| dom = e.gcd(@phi) if dom == 1 then - @e = e - break + enc << e end end + @e = enc.sample - @d = RSA.mod_inv(@e, @n) + @d = RSA.n_inv(@e, @n) + puts "e=#{@e} d=#{@d}" end def pubkey @@ -30,36 +32,59 @@ module RSA end end - class Data < Array + class Data attr_reader :data def initialize(data) - super data - if data.class == String then - self = data.split("") - self = self.map do |c| - c.to_i + @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 inspect - self.join " " + 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(key) - e, mod = key.pubkey + def encrypt(pubkey) + e, n = pubkey crypt = [] - text.split("").each_with_index do |c, i| - c = c.ord ** e - c %= mod - crypt << charint + @data.each do |c| + cr = (c ** e) % n + crypt << cr end return crypt end - def encrypt!(key) - self = self.encrypt(key) + 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 diff --git a/ma5/rsa/test.rb b/ma5/rsa/test.rb new file mode 100755 index 0000000..787ffc3 --- /dev/null +++ b/ma5/rsa/test.rb @@ -0,0 +1,27 @@ +#!/usr/bin/ruby -w + +require_relative "rsa" + +Primes = File.read("primes.txt").chomp.split(",").map do |pstr| + pstr.to_i +end + +puts "Fetching random primes..." +p1, p2 = Primes.sample, Primes.sample +p1, p2 = 11, 13 +puts "p1=#{p1}, p2=#{p2}" +puts + +key = RSA::Key.new(p1, p2) +print "Message to be encrypted: " +msg = gets.chomp + +data = RSA::Data.new(msg) + +data.encrypt!(key.pubkey) +puts "Encrypted bytes: #{data.raw}" + +data.decrypt!(key.privkey) +puts data.raw +p data.data +