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

66 lines
903 B

3 years ago
module RSA
def self.mod_inv(a, m)
(1..m).each{|x| break x if (a*x % m == 1)}
end
class Key
def initialize(p1, p2)
3 years ago
puts "Generating key pair..."
3 years ago
@n = p1 * p2
@phi = (p1-1)*(p2-1)
(2...@phi).each do |e|
3 years ago
dom = e.gcd(@phi)
if dom == 1 then
3 years ago
@e = e
break
end
end
3 years ago
@d = RSA.mod_inv(@e, @n)
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 < Array
attr_reader :data
def initialize(data)
super data
if data.class == String then
self = data.split("")
self = self.map do |c|
c.to_i
end
end
3 years ago
end
3 years ago
def inspect
self.join " "
end
3 years ago
3 years ago
def encrypt(key)
e, mod = key.pubkey
crypt = []
text.split("").each_with_index do |c, i|
c = c.ord ** e
c %= mod
crypt << charint
end
return crypt
end
def encrypt!(key)
self = self.encrypt(key)
end
3 years ago
end
end