summaryrefslogtreecommitdiff
path: root/lib/srp/client.rb
blob: 9a271747e4be52a15164acb6353c101023be8e10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
require File.expand_path(File.dirname(__FILE__) + '/util')

module SRP
  class Client

    include Util

    attr_reader :salt, :verifier

    def initialize(username, password)
      @username = username
      @password = password
      @salt = bigrand(10).hex
      @multiplier = multiplier # let's cache it
      calculate_verifier
    end

    def authenticate(server, username, password)
      x = calculate_x(username, password, salt)
      a = bigrand(32).hex
      aa = modpow(GENERATOR, a, PRIME_N) # A = g^a (mod N)
      bb, u = server.initialize_auth(aa)
      client_s = calculate_client_s(x, a, bb, u)
      server.authenticate(aa, calculate_m(aa,bb,client_s))
    end

    protected
    def calculate_verifier
      x = calculate_x(@username, @password, @salt)
      @verifier = modpow(GENERATOR, x, PRIME_N)
    end

    def calculate_x(username, password, salt)
      shex = '%x' % [salt]
      spad = if shex.length.odd? then '0' else '' end
      sha256_hex(spad + shex + sha256_str([username, password].join(':'))).hex
    end

    def calculate_client_s(x, a, bb, u)
      base = bb
      base += PRIME_N * @multiplier
      base -= modpow(GENERATOR, x, PRIME_N) * @multiplier
      base = base % PRIME_N
      modpow(base, x * u + a, PRIME_N)
    end
  end
end