module Base64Token
Constants
- VERSION
Public Class Methods
encryption_key=(key)
click to toggle source
# File lib/base64_token.rb, line 33 def encryption_key=(key) @encryption_key = key @crypto_box = nil end
generate(**hash)
click to toggle source
# File lib/base64_token.rb, line 14 def generate(**hash) json = JSON.generate(hash) cipher = encrypt(json) Base64.urlsafe_encode64(cipher) end
generate_key()
click to toggle source
# File lib/base64_token.rb, line 27 def generate_key Base64.strict_encode64( RbNaCl::Random.random_bytes(RbNaCl::SecretBox.key_bytes) ) end
parse(token)
click to toggle source
# File lib/base64_token.rb, line 20 def parse(token) return {} if !token || token.strip.empty? cipher = base64_decode(token) json = decrypt(cipher) JSON.parse(json).map { |k, v| [k.to_sym, v] }.to_h end
Private Class Methods
base64_decode(string)
click to toggle source
# File lib/base64_token.rb, line 44 def base64_decode(string) Base64.urlsafe_decode64(string) rescue ArgumentError => e raise Error, e.message end
crypto_box()
click to toggle source
# File lib/base64_token.rb, line 56 def crypto_box @crypto_box ||= begin unless @encryption_key raise ConfigurationError, 'Encryption key not set.' end key = Base64.decode64(@encryption_key) RbNaCl::SimpleBox.from_secret_key(key) end end
decrypt(ciphertext)
click to toggle source
# File lib/base64_token.rb, line 50 def decrypt(ciphertext) crypto_box.decrypt(ciphertext) rescue RbNaCl::CryptoError, RbNaCl::LengthError => e raise Error, e.message end
encrypt(plaintext)
click to toggle source
# File lib/base64_token.rb, line 40 def encrypt(plaintext) crypto_box.encrypt(plaintext) end