Class: UCenter::AuthCode

Inherits:
Object
  • Object
show all
Defined in:
lib/ucenter_authcode.rb

Overview

用类包装来防止方法间变量修改

Constant Summary collapse

KeyLength =
4

Instance Method Summary collapse

Instance Method Details

#authcode(key, string) ⇒ Object



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
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ucenter_authcode.rb', line 16

def authcode key, string
  # 拆分key,并各自做md5
  key = md5(key)
  key_left, key_right = md5(key[0, 16]), md5(key[16, 16])

  # 拆分string auth和content部分
  string_auth, string_content = string[0, KeyLength], string[KeyLength..-1]

  # 从key_crypt抽取box
  key_crypt = key_left + md5(key_left + string_auth)
  key_crypt_length = key_crypt.length
  rndkey = []
  0.upto(255) do |i|
    rndkey[i] = (key_crypt[i % key_crypt_length]).ord
  end
  a = b = 0
  box = (0..255).to_a
  while b < 256 do
    a = (a + box[b] + rndkey[b]) % 256
    box[b], box[a] = box[a], box[b]
    b +=1
  end

  # 联合key_crypt和key_content解密出result
  string_content_ords = base64_url_decode(string_content).bytes.to_a
  string_content_ords_length = string_content_ords.length
  a = b = string_idx = 0
  result = ""
  while string_idx < string_content_ords_length
    a = (a + 1) % 256
    b = (b + box[a]) % 256
    box[a], box[b] = box[b], box[a]
    result << (string_content_ords[string_idx] ^ (box[(box[a] + box[b]) % 256])).chr
    string_idx +=1
  end

  result_time_valided = (result[0, 10] == '0'*10) || (result[0, 10].to_i - Time.now.to_i  >  0)
  result_string_valided = result[10, 16] == md5("#{result[26..-1]}#{key_right}")[0, 16] # 重新加密和string对比验证
  if (result_time_valided  && result_string_valided)
    return result[26..-1]
  else
    return ''
  end
end

#microtimeObject



61
62
63
64
65
66
# File 'lib/ucenter_authcode.rb', line 61

def microtime
  epoch_mirco = Time.now.to_f
  epoch_full = Time.now.to_i
  epoch_fraction = epoch_mirco - epoch_full
  epoch_fraction.to_s + ' ' + epoch_full.to_s
end