Sha256: 9881fe30303d56cd0888b8553f4745da197cf0b1010ad4598f36bc6a884bfd12

Contents?: true

Size: 1.53 KB

Versions: 2

Compression:

Stored size: 1.53 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
    ENV.fetch('SECRET') { puts '* Warn: ENV SECRET not set'; 'foo' }
  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 bcrypt plain, check=nil
    if check
      BCrypt::Password.new(check) == [plain, secret].join('')
    else
      BCrypt::Password.create(plain + secret)
    end
  end

  # Crypt.encrypt('secret')
  # Crypt.encrypt('secret', ttl:1.hour, password:'pa$$w0rd')
  def encrypt(data, opts={})
    opts = opts.to_opts!(:ttl, :password)

    payload = { data:data }
    payload[:ttl] = Time.now.to_i + opts.ttl if opts.ttl
    JWT.encode payload, secret+opts.password.to_s, ALGORITHM
  end

  # Crypt.decrypt('secret')
  # Crypt.decrypt('secret', password:'pa$$w0rd')
  def decrypt(token, opts={})
    opts = opts.to_opts!(:password)

    token_data = JWT.decode token, secret+opts.password.to_s, true, { :algorithm => ALGORITHM }
    data = token_data[0]
    raise "Crypted 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

2 entries across 2 versions & 1 rubygems

Version Path
lux-fw-0.2.3 ./lib/common/crypt.rb
lux-fw-0.2.1 ./lib/common/crypt.rb