Old high school files. Lessson notes/codes/projects etc.
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.
hsf/ma5/rsa/rsa.rb

105 lines
1.5 KiB

3 years ago
module RSA
3 years ago
def self.egcd(a, b)
if a == 0 then
return b, 0, 1
else
g, y ,x = self.egcd(b % a, a)
return g, x - (b.to_i / a.to_i)*y, y
end
end
def self.modinv(a, m)
g, x, y = self.egcd(a, m)
if g != 1 then
raise "Mod inv does not exist"
else
return x % m
end
3 years ago
end
class Key
def initialize(p1, p2)
3 years ago
puts "Generating key pair..."
3 years ago
@n = p1 * p2
3 years ago
@phi = (p1-1)*(p2-1)
3 years ago
3 years ago
enc = []
3 years ago
(2...@phi).each do |e|
3 years ago
dom = e.gcd(@phi)
if dom == 1 then
3 years ago
enc << e
3 years ago
end
end
3 years ago
@e = enc.sample
3 years ago
@d = RSA.modinv(@e, @phi)
3 years ago
3 years ago
puts "e: #{@e} d: #{@d}"
3 years ago
end
def pubkey
3 years ago
return @e, @n
3 years ago
end
def privkey
3 years ago
return @d, @n
3 years ago
end
end
3 years ago
class Data
3 years ago
attr_reader :data
def initialize(data)
3 years ago
@data = data
if data.is_a? String then
@data = @data.split("").map do |c|
c.ord.to_i
3 years ago
end
end
3 years ago
puts "Generated bytes: #{self.raw}"
3 years ago
end
3 years ago
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}"
3 years ago
end
3 years ago
3 years ago
def encrypt(pubkey)
e, n = pubkey
3 years ago
crypt = []
3 years ago
@data.each do |c|
cr = (c ** e) % n
crypt << cr
3 years ago
end
return crypt
end
3 years ago
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)
3 years ago
end
3 years ago
end
end