Class: Discordrb::CachedToken

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

Overview

Represents a cached token with encryption data

Instance Method Summary collapse

Constructor Details

#initialize(data = nil) ⇒ CachedToken

Returns a new instance of CachedToken.



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/discordrb/token_cache.rb', line 13

def initialize(data = nil)
  if data
    @verify_salt = Base64.decode64(data['verify_salt'])
    @password_hash = Base64.decode64(data['password_hash'])
    @encrypt_salt = Base64.decode64(data['encrypt_salt'])
    @iv = Base64.decode64(data['iv'])
    @encrypted_token = Base64.decode64(data['encrypted_token'])
  else
    generate_salts
  end
end

Instance Method Details

#dataObject



25
26
27
28
29
30
31
32
33
# File 'lib/discordrb/token_cache.rb', line 25

def data
  {
    verify_salt: Base64.encode64(@verify_salt),
    password_hash: Base64.encode64(@password_hash),
    encrypt_salt: Base64.encode64(@encrypt_salt),
    iv: Base64.encode64(@iv),
    encrypted_token: Base64.encode64(@encrypted_token)
  }
end

#decrypt_token(password) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/discordrb/token_cache.rb', line 52

def decrypt_token(password)
  key = obtain_key(password)
  decipher = OpenSSL::Cipher::AES256.new(:CBC)
  decipher.decrypt
  decipher.key = key
  decipher.iv = @iv
  decipher.update(@encrypted_token) + decipher.final
end

#encrypt_token(password, token) ⇒ Object



61
62
63
64
65
66
67
68
# File 'lib/discordrb/token_cache.rb', line 61

def encrypt_token(password, token)
  key = obtain_key(password)
  cipher = OpenSSL::Cipher::AES256.new(:CBC)
  cipher.encrypt
  cipher.key = key
  @iv = cipher.random_iv
  @encrypted_token = cipher.update(token) + cipher.final
end

#generate_saltsObject



47
48
49
50
# File 'lib/discordrb/token_cache.rb', line 47

def generate_salts
  @verify_salt = OpenSSL::Random.random_bytes(KEYLEN)
  @encrypt_salt = OpenSSL::Random.random_bytes(KEYLEN)
end

#generate_verify_hash(password) ⇒ Object



39
40
41
# File 'lib/discordrb/token_cache.rb', line 39

def generate_verify_hash(password)
  @password_hash = hash_password(password)
end

#obtain_key(password) ⇒ Object



43
44
45
# File 'lib/discordrb/token_cache.rb', line 43

def obtain_key(password)
  @key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(password, @encrypt_salt, 300_000, KEYLEN)
end

#test_token(token) ⇒ Object



70
71
72
# File 'lib/discordrb/token_cache.rb', line 70

def test_token(token)
  Discordrb::API.gateway(token)
end

#verify_password(password) ⇒ Object



35
36
37
# File 'lib/discordrb/token_cache.rb', line 35

def verify_password(password)
  hash_password(password) == @password_hash
end