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

108 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
3 years ago
attr_accessor :e, :d, :n
3 years ago
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
end
3 years ago
def inspect
3 years ago
"n=#{@n} e=#{@e} d=#{@d}"
3 years ago
end
3 years ago
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
end
3 years ago
def raw
str = ""
@data.each do |byte|
str += "\\x#{byte.to_s 16}"
end
return str
end
3 years ago
def to_si
return @data.join " "
end
def to_s
3 years ago
pattern = "c" * @data.length
3 years ago
return @data.pack(pattern)
3 years ago
end
3 years ago
3 years ago
private def crypt(key)
e, n = key
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 encrypt(key)
self.crypt(key.pubkey)
end
3 years ago
3 years ago
def decrypt(key)
self.crypt(key.privkey)
3 years ago
end
3 years ago
def encrypt!(key)
@data = self.encrypt(key)
3 years ago
end
3 years ago
def decrypt!(key)
@data = self.decrypt(key)
3 years ago
end
3 years ago
end
end