master
E. Almqvist 3 years ago
parent bdc1bd17dc
commit 6730bf4d0f
  1. 0
      ma5/rsa/brute.rb
  2. 65
      ma5/rsa/rsa.rb
  3. 27
      ma5/rsa/test.rb

@ -1,5 +1,5 @@
module RSA 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)} (1..m).each{|x| break x if (a*x % m == 1)}
end end
@ -9,16 +9,18 @@ module RSA
@n = p1 * p2 @n = p1 * p2
@phi = (p1-1)*(p2-1) @phi = (p1-1)*(p2-1)
enc = []
(2...@phi).each do |e| (2...@phi).each do |e|
dom = e.gcd(@phi) dom = e.gcd(@phi)
if dom == 1 then if dom == 1 then
@e = e enc << e
break
end end
end end
@e = enc.sample
@d = RSA.mod_inv(@e, @n) @d = RSA.n_inv(@e, @n)
puts "e=#{@e} d=#{@d}"
end end
def pubkey def pubkey
@ -30,36 +32,59 @@ module RSA
end end
end end
class Data < Array class Data
attr_reader :data attr_reader :data
def initialize(data) def initialize(data)
super data @data = data
if data.class == String then if data.is_a? String then
self = data.split("") @data = @data.split("").map do |c|
self = self.map do |c| c.ord.to_i
c.to_i
end end
end end
puts "Generated bytearray: #{@data}"
end end
def inspect def raw
self.join " " 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 end
def encrypt(key) def encrypt(pubkey)
e, mod = key.pubkey e, n = pubkey
crypt = [] crypt = []
text.split("").each_with_index do |c, i| @data.each do |c|
c = c.ord ** e cr = (c ** e) % n
c %= mod crypt << cr
crypt << charint
end end
return crypt return crypt
end end
def encrypt!(key) def decrypt(privkey)
self = self.encrypt(key) 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 end
end end

@ -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
Loading…
Cancel
Save