Skip to content
This repository has been archived by the owner on Sep 12, 2018. It is now read-only.

Commit

Permalink
Implemented the RSA::Math.log, .log2 and .log256 methods.
Browse files Browse the repository at this point in the history
  • Loading branch information
artob committed Sep 6, 2010
1 parent 3c6471e commit b7b203d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
10 changes: 5 additions & 5 deletions lib/rsa/key_pair.rb
Expand Up @@ -66,15 +66,15 @@ def valid?
#
# @return [Integer]
def bytesize
::Math.log(modulus, 256).ceil
Math.log256(modulus).ceil
end

##
# Returns the bit size of this key pair.
#
# @return [Integer]
def bitsize
::Math.log2(modulus).ceil
Math.log2(modulus).ceil
end
alias_method :size, :bitsize

Expand Down Expand Up @@ -103,7 +103,7 @@ def encrypt(plaintext, options = {})
else raise ArgumentError, plaintext.inspect
end
ciphertext = PKCS1.rsaep(public_key, plaintext)
PKCS1.i2osp(ciphertext, ::Math.log(ciphertext, 256).ceil)
PKCS1.i2osp(ciphertext, Math.log256(ciphertext).ceil)
end

##
Expand All @@ -122,7 +122,7 @@ def decrypt(ciphertext, options = {})
else raise ArgumentError, ciphertext.inspect
end
plaintext = PKCS1.rsadp(private_key, ciphertext)
PKCS1.i2osp(plaintext, ::Math.log(plaintext, 256).ceil)
PKCS1.i2osp(plaintext, Math.log256(plaintext).ceil)
end

##
Expand All @@ -140,7 +140,7 @@ def sign(plaintext, options = {})
else raise ArgumentError, plaintext.inspect
end
signature = PKCS1.rsasp1(private_key, plaintext)
PKCS1.i2osp(signature, ::Math.log(signature, 256).ceil)
PKCS1.i2osp(signature, Math.log256(signature).ceil)
end
end # class KeyPair
end # module RSA
36 changes: 32 additions & 4 deletions lib/rsa/math.rb
Expand Up @@ -4,10 +4,6 @@ module RSA
module Math
extend ::Math

class << self
public :log, :log2
end

##
# Performs a primality test on the integer `n`, returning `true` if it
# is a prime.
Expand Down Expand Up @@ -68,5 +64,37 @@ def self.modpow(base, exponent, modulus)
def self.phi(n)
1 + (2...n).count { |i| i.gcd(n).eql?(1) }
end

##
# Returns the binary logarithm of `n`.
#
# @param [Integer] n
# @return [Float]
# @see http://en.wikipedia.org/wiki/Binary_logarithm
def self.log2(n)
::Math.log2(n)
end

##
# Returns the base-256 logarithm of `n`.
#
# @param [Integer] n
# @return [Float]
# @see http://en.wikipedia.org/wiki/Logarithm
def self.log256(n)
::Math.log(n, 256)
end

##
# Returns the natural logarithm of `n`. If the optional argument `b` is
# given, it will be used as the base of the logarithm.
#
# @param [Integer] n
# @param [Integer] b
# @return [Float]
# @see http://en.wikipedia.org/wiki/Natural_logarithm
def self.log(n, b = nil)
b ? ::Math.log(n, b) : ::Math.log(n)
end
end
end

0 comments on commit b7b203d

Please sign in to comment.