Sha256: 08e20a86f7b92763b5a0896dafde4d08a8a34beecb642923ea5fc56726366dcd
Contents?: true
Size: 1.61 KB
Versions: 1
Compression:
Stored size: 1.61 KB
Contents
# frozen_string_literal: true # @author: Dino Reic # @description: # module for easy and convenient access to frequently used crypt operations require 'openssl' require 'base64' require 'digest/md5' require 'securerandom' module Crypt extend self ALGORITHM = 'HS512' def secret Lux.env('SECRET') end def base64(str) Base64.urlsafe_encode64(str) end def uid SecureRandom.hex end def sha1(str) Digest::SHA1.hexdigest(str.to_s + secret) end def md5(str) Digest::MD5.hexdigest(str.to_s + secret) end def bc(str) BCrypt::Password.create(str + secret) end # Crypt.encrypt('secret') # Crypt.encrypt('secret', ttl:1.hour, password:'pa$$w0rd') def encrypt(data, opts={}) diff = opts.keys - [:ttl, :password] raise 'Unallowed key(s) found %s' % diff.join(', ') if diff.length > 0 payload = { data:data } payload[:ttl] = Time.now.to_i + opts[:ttl] if opts[:ttl] hmac_secret = "#{secret}#{opts.delete(:password)}" JWT.encode payload, hmac_secret, ALGORITHM end # Crypt.decrypt('secret') # Crypt.decrypt('secret', password:'pa$$w0rd') def decrypt(token, opts={}) diff = opts.keys - [:password] raise 'Unallowed key(s) found %s' % diff.join(', ') if diff.length > 0 hmac_secret = "#{secret}#{opts.delete(:password)}" token_data = JWT.decode token, hmac_secret, true, { :algorithm => ALGORITHM } data = token_data[0] raise "Crpted data expired before #{Time.now.to_i - data['ttl']} seconds" if data['ttl'] && data['ttl'] < Time.now.to_i data['data'] end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
lux-fw-0.1.17 | ./lib/common/crypt.rb |