Class: Crypto::Commons

Inherits:
Object
  • Object
show all
Defined in:
lib/crypto/commons.rb

Constant Summary collapse

SALT_SPLITTER =
'$$'.freeze

Class Method Summary collapse

Class Method Details

.checksum(text) ⇒ Object



44
45
46
47
# File 'lib/crypto/commons.rb', line 44

def self.checksum(text)
  text = text.to_s unless text.is_a? String
  Digest::SHA2.new(256).hexdigest(text)
end

.checksum512(text) ⇒ Object



49
50
51
52
# File 'lib/crypto/commons.rb', line 49

def self.checksum512(text)
  text = text.to_s unless text.is_a? String
  Digest::SHA2.new(512).hexdigest(text)
end

.decrypt(text, secret = Crypto.secret_key_base.to_s, cipher: 'aes-256-gcm') ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/crypto/commons.rb', line 17

def self.decrypt(text, secret = Crypto.secret_key_base.to_s, cipher: 'aes-256-gcm')
  salt, data = text.split SALT_SPLITTER

  len   = ActiveSupport::MessageEncryptor.key_len(cipher)
  key   = ActiveSupport::KeyGenerator.new(secret)
                                     .generate_key salt, len
  crypt = ActiveSupport::MessageEncryptor.new(key, cipher: cipher)
  crypt.decrypt_and_verify data
end

.encrypt(text, secret = Crypto.secret_key_base.to_s, cipher: 'aes-256-gcm') ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/crypto/commons.rb', line 5

def self.encrypt(text, secret = Crypto.secret_key_base.to_s, cipher: 'aes-256-gcm')
  text = text.to_s unless text.is_a? String

  len   = ActiveSupport::MessageEncryptor.key_len(cipher)
  salt  = SecureRandom.hex len
  key   = ActiveSupport::KeyGenerator.new(secret)
                                     .generate_key salt, len
  crypt = ActiveSupport::MessageEncryptor.new(key, cipher: cipher)
  encrypted_data = crypt.encrypt_and_sign text
  "#{salt}#{SALT_SPLITTER}#{encrypted_data}"
end

.hash(text) ⇒ Object



27
28
29
30
31
32
# File 'lib/crypto/commons.rb', line 27

def self.hash(text)
  text = text.to_s unless text.is_a? String
  cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
           BCrypt::Engine.cost
  BCrypt::Password.create(text, cost: cost)
end

.hash_compare(hash, text) ⇒ Object



34
35
36
37
# File 'lib/crypto/commons.rb', line 34

def self.hash_compare(hash, text)
  password = BCrypt::Password.new(hash)
  password == text
end

.md5_digest(text) ⇒ Object



39
40
41
42
# File 'lib/crypto/commons.rb', line 39

def self.md5_digest(text)
  text = text.to_s unless text.is_a? String
  Digest::MD5.hexdigest(text)
end

.rsa_seal(private_key, passphrase, text) ⇒ Object



58
59
60
61
62
# File 'lib/crypto/commons.rb', line 58

def self.rsa_seal(private_key, passphrase, text)
  text = text.to_s unless text.is_a? String
  key = Crypto::RSAKey.new private_key, passphrase
  key.seal(text)
end

.sha256(secret_key, text) ⇒ Object



54
55
56
# File 'lib/crypto/commons.rb', line 54

def self.sha256(secret_key, text)
  OpenSSL::HMAC.hexdigest('sha256', secret_key, text)
end