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

91 lines
1.3 KiB

3 years ago
module RSA
3 years ago
def self.n_inv(a, m)
3 years ago
(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)
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
3 years ago
@d = RSA.n_inv(@e, @n)
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 bytearray: #{@data}"
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