mirror of https://github.com/E-Almqvist/hsf
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
1.3 KiB
90 lines
1.3 KiB
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
|
|
|
|
@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
|
|
|