Class: Tokenify::Token

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(secret, salt, data) ⇒ Token

Returns a new instance of Token.



8
9
10
11
12
# File 'lib/tokenify/token.rb', line 8

def initialize(secret, salt, data)
  @secret = secret
  @salt = salt
  @data = data
end

Instance Attribute Details

#encryptedObject (readonly)

Returns the value of attribute encrypted.



6
7
8
# File 'lib/tokenify/token.rb', line 6

def encrypted
  @encrypted
end

#plainObject (readonly)

Returns the value of attribute plain.



6
7
8
# File 'lib/tokenify/token.rb', line 6

def plain
  @plain
end

Class Method Details

.cipher(mode, key, data, iv = nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/tokenify/token.rb', line 14

def self.cipher(mode, key, data, iv = nil)
  cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc').send(mode)
  cipher.key = Digest::SHA256.hexdigest(key)
  if iv 
    cipher.iv = iv
    cipher.update(data) << cipher.final
  else
    cipher.iv = iv = cipher.random_iv
    iv + cipher.update(data) + cipher.final
  end
end

Instance Method Details

#decrypt(is_encoded = true) ⇒ Object



35
36
37
38
39
# File 'lib/tokenify/token.rb', line 35

def decrypt(is_encoded = true)
  decoded = is_encoded ? Base64.urlsafe_decode64(@data) : @data
  iv = decoded.slice!(0,16)
  @plain = Token.cipher(:decrypt, "#{@secret}:#{@salt}", decoded, iv)
end

#encodedObject



31
32
33
# File 'lib/tokenify/token.rb', line 31

def encoded
  Base64.urlsafe_encode64(@encrypted)
end

#generateObject



26
27
28
29
# File 'lib/tokenify/token.rb', line 26

def generate
  @encrypted = Token.cipher(:encrypt, "#{@secret}:#{@salt}", @data)
  self
end