Module: StringEnhancer::Encryption

Defined in:
lib/string_enhancer/encryption.rb

Class Method Summary collapse

Class Method Details

.decrypt(encrypted_str, key, algorithm: 'AES-256-CBC') ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/string_enhancer/encryption.rb', line 17

def decrypt(encrypted_str, key, algorithm: 'AES-256-CBC')
  decoded = Base64.strict_decode64(encrypted_str)
  cipher = OpenSSL::Cipher.new(algorithm)
  cipher.decrypt
  cipher.key = Digest::SHA256.digest(key)
  
  iv = decoded[0...cipher.iv_len]
  encrypted = decoded[cipher.iv_len..-1]
  
  cipher.iv = iv
  cipher.update(encrypted) + cipher.final
end

.encrypt(str, key, algorithm: 'AES-256-CBC') ⇒ Object



7
8
9
10
11
12
13
14
15
# File 'lib/string_enhancer/encryption.rb', line 7

def encrypt(str, key, algorithm: 'AES-256-CBC')
  cipher = OpenSSL::Cipher.new(algorithm)
  cipher.encrypt
  cipher.key = Digest::SHA256.digest(key)
  iv = cipher.random_iv
  
  encrypted = cipher.update(str) + cipher.final
  Base64.strict_encode64(iv + encrypted)
end

.generate_salt(length = 16) ⇒ Object



53
54
55
# File 'lib/string_enhancer/encryption.rb', line 53

def generate_salt(length = 16)
  OpenSSL::Random.random_bytes(length)
end

.hash(str, algorithm: :sha256) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/string_enhancer/encryption.rb', line 30

def hash(str, algorithm: :sha256)
  case algorithm
  when :sha256
    Digest::SHA256.hexdigest(str)
  when :sha512
    Digest::SHA512.hexdigest(str)
  when :md5
    Digest::MD5.hexdigest(str)
  else
    raise Error, "Unsupported hash algorithm: #{algorithm}"
  end
end

.pbkdf2(str, salt, iterations: 10000, key_length: 32) ⇒ Object



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

def pbkdf2(str, salt, iterations: 10000, key_length: 32)
  OpenSSL::PKCS5.pbkdf2_hmac_sha1(
    str,
    salt,
    iterations,
    key_length
  )
end

.secure_compare(str1, str2) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/string_enhancer/encryption.rb', line 43

def secure_compare(str1, str2)
  return false unless str1.bytesize == str2.bytesize
  
  result = 0
  str1.bytes.zip(str2.bytes) do |b1, b2|
    result |= b1 ^ b2
  end
  result.zero?
end