Module: Crypt

Extended by:
Crypt
Included in:
Crypt
Defined in:
lib/common/crypt.rb

Constant Summary collapse

ALGORITHM =
'HS512'

Instance Method Summary collapse

Instance Method Details

#base64(str) ⇒ Object



21
22
23
# File 'lib/common/crypt.rb', line 21

def base64 str
  Base64.urlsafe_encode64(str)
end

#bcrypt(plain, check = nil) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/common/crypt.rb', line 37

def bcrypt plain, check=nil
  if check
    BCrypt::Password.new(check) == [plain, secret].join('')
  else
    BCrypt::Password.create(plain + secret)
  end
end

#decrypt(token, opts = {}) ⇒ Object

Crypt.decrypt(‘secret’) Crypt.decrypt(‘secret’, password:‘pa$$w0rd’)



57
58
59
60
61
62
63
64
# File 'lib/common/crypt.rb', line 57

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

#encrypt(data, opts = {}) ⇒ Object

Crypt.encrypt(‘secret’) Crypt.encrypt(‘secret’, ttl:1.hour, password:‘pa$$w0rd’)



47
48
49
50
51
52
53
# File 'lib/common/crypt.rb', line 47

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

#md5(str) ⇒ Object



33
34
35
# File 'lib/common/crypt.rb', line 33

def md5 str
  Digest::MD5.hexdigest(str.to_s + secret)
end

#secretObject



17
18
19
# File 'lib/common/crypt.rb', line 17

def secret
  ENV.fetch('SECRET') { puts '* Warn: ENV SECRET not set'; 'foo' }
end

#sha1(str) ⇒ Object



29
30
31
# File 'lib/common/crypt.rb', line 29

def sha1 str
  Digest::SHA1.hexdigest(str.to_s + secret)
end

#uidObject



25
26
27
# File 'lib/common/crypt.rb', line 25

def uid
  SecureRandom.hex
end