Sha256: 834ee67267a4abec63a13cef768e39a44dd972304e647d1751918da6e80da640
Contents?: true
Size: 1.83 KB
Versions: 1
Compression:
Stored size: 1.83 KB
Contents
require "cryptify/version" require 'prime' module Cryptify # # RSA implementation class. # class Rsa # # Attributes used. # # @p, @q # Random prime numbers. # # @e # Public exponent # # @n # @p and @q computation # # @d # Inverse multiplicative # # # Construtor. # def initialize prime_list = Prime.take(100) # Generate p and q @p = prime_list.sample prime_list.delete(@p) @q = prime_list.sample # Compute n. @n = @p * @q # 1.3 Calculate `z`. @z = (@p - 1) * (@q - 1) # 1.4 Calculate coprime. @z.downto(0) do |i| if self.is_coprime(i, @z) @e = i; break; end end # 1.5 Modular inverse @d = modinv(@e, @z) end # # Encrypt a message. # def encrypt(message) # Represent the message as a positive integer. # message = 29 # Compute the ciphertext c to b. (message ** @e) % @n end # # Decrypt message. # def decrypt(encrypted_message) # Uses his private key (n, d) to compute: (encrypted_message ** @d) % @n end # # Checks whether `a` and `b` are coprime. # def is_coprime(a, b) # Cycle from 2 until the smaller number of a and b. 2.upto([a, b].min) do |i| # If both modulus with `i` are equal to `0` # then, the numbers are no coprime. if a % i == b % i && a % i == 0 return false end end return true end # # Returns a triple (g, x, y), such that ax + by = g = gcd(a, b). # Assumes a, b >= 0, and that at least one of them is > 0. # Bounds on output values: |x|, |y| < [a, b].max # def egcd(a, b) if a == 0 return [b, 0, 1] else g, y, x = egcd(b % a, a) return [g, x - (b / a) * y, y] end end # # Modular inverse. # def modinv(a, m) g, x, y = self.egcd(a, m) return g != 1 ? nil : x % m end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
cryptify-0.0.2 | lib/cryptify.rb |