class OpenID::DiffieHellman

Encapsulates a Diffie-Hellman key exchange. This class is used internally by both the consumer and server objects.

Read more about Diffie-Hellman on wikipedia: en.wikipedia.org/wiki/Diffie-Hellman

Attributes

generator[R]
modulus[R]
public[R]

Public Class Methods

from_defaults() click to toggle source

A new DiffieHellman object, using the modulus and generator from the OpenID specification

# File lib/openid/dh.rb, line 22
def DiffieHellman.from_defaults
  DiffieHellman.new(@@default_mod, @@default_gen)
end
new(modulus=nil, generator=nil, priv=nil) click to toggle source
# File lib/openid/dh.rb, line 26
def initialize(modulus=nil, generator=nil, priv=nil)
  @modulus = modulus.nil? ? @@default_mod : modulus
  @generator = generator.nil? ? @@default_gen : generator
  set_private(priv.nil? ? OpenID::CryptUtil.rand(@modulus-2) + 1 : priv)
end

Private Class Methods

powermod(x, n, q) click to toggle source

This code is taken from this post: <blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/19098> by Eric Lee Green.

# File lib/openid/dh.rb, line 71
def DiffieHellman.powermod(x, n, q)
  counter=0
  n_p=n
  y_p=1
  z_p=x
  while n_p != 0
    if n_p[0]==1
      y_p=(y_p*z_p) % q
    end
    n_p = n_p >> 1
    z_p = (z_p * z_p) % q
    counter += 1
  end
  return y_p
end
strxor(s, t) click to toggle source
# File lib/openid/dh.rb, line 53
def DiffieHellman.strxor(s, t)
  if s.length != t.length
    raise ArgumentError, "strxor: lengths don't match. " +
      "Inputs were #{s.inspect} and #{t.inspect}"
  end

  if String.method_defined? :bytes
    s.bytes.to_a.zip(t.bytes.to_a).map{|sb,tb| sb^tb}.pack('C*')
  else
    indices = 0...(s.length)
    chrs = indices.collect {|i| (s[i]^t[i]).chr}
    chrs.join("")
  end
end

Public Instance Methods

get_shared_secret(composite) click to toggle source
# File lib/openid/dh.rb, line 32
def get_shared_secret(composite)
  DiffieHellman.powermod(composite, @private, @modulus)
end
using_default_values?() click to toggle source
# File lib/openid/dh.rb, line 43
def using_default_values?
  @generator == @@default_gen && @modulus == @@default_mod
end
xor_secret(algorithm, composite, secret) click to toggle source
# File lib/openid/dh.rb, line 36
def xor_secret(algorithm, composite, secret)
  dh_shared = get_shared_secret(composite)
  packed_dh_shared = OpenID::CryptUtil.num_to_binary(dh_shared)
  hashed_dh_shared = algorithm.call(packed_dh_shared)
  return DiffieHellman.strxor(secret, hashed_dh_shared)
end

Private Instance Methods

set_private(priv) click to toggle source
# File lib/openid/dh.rb, line 48
def set_private(priv)
  @private = priv
  @public = DiffieHellman.powermod(@generator, @private, @modulus)
end