Class: DiffieHellman

Inherits:
Object
  • Object
show all
Defined in:
lib/syndi/irc/sasl/diffie_hellman.rb

Overview

This code exists in the public domain.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(p, g, q) ⇒ DiffieHellman

p is the prime, g the generator and q order of the subgroup



8
9
10
11
12
# File 'lib/syndi/irc/sasl/diffie_hellman.rb', line 8

def initialize p, g, q
  @p = p
  @g = g
  @q = q
end

Instance Attribute Details

#eObject (readonly)

Returns the value of attribute e.



5
6
7
# File 'lib/syndi/irc/sasl/diffie_hellman.rb', line 5

def e
  @e
end

#gObject (readonly)

Returns the value of attribute g.



5
6
7
# File 'lib/syndi/irc/sasl/diffie_hellman.rb', line 5

def g
  @g
end

#pObject (readonly)

Returns the value of attribute p.



5
6
7
# File 'lib/syndi/irc/sasl/diffie_hellman.rb', line 5

def p
  @p
end

#qObject (readonly)

Returns the value of attribute q.



5
6
7
# File 'lib/syndi/irc/sasl/diffie_hellman.rb', line 5

def q
  @q
end

#xObject (readonly)

Returns the value of attribute x.



5
6
7
# File 'lib/syndi/irc/sasl/diffie_hellman.rb', line 5

def x
  @x
end

Instance Method Details

#generate(tries = 16) ⇒ Object

generate the [secret] random value and the public key

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
22
# File 'lib/syndi/irc/sasl/diffie_hellman.rb', line 15

def generate tries=16
  tries.times do
    @x = rand(@q)
    @e = self.g.mod_exp(@x, self.p)
    return @e if self.valid?
  end
  raise ArgumentError, "can't generate valid e"
end

#secret(f) ⇒ Object

compute the shared secret, given the public key



30
31
32
# File 'lib/syndi/irc/sasl/diffie_hellman.rb', line 30

def secret f
  f.mod_exp(self.x, self.p)
end

#valid?(_e = self.e) ⇒ Boolean

validate a public key

Returns:

  • (Boolean)


25
26
27
# File 'lib/syndi/irc/sasl/diffie_hellman.rb', line 25

def valid?(_e = self.e)
  _e and _e.between?(2, self.p-2) and _e.bits_set > 1
end