require 'securerandom'
require 'openssl'

module Roclobak
  module Security
    def self.generate_key_derivation_salt
      SecureRandom.random_bytes 16
    end

    def self.derive_key_from_password(password, salt)
      password = password.encode 'UTF-8'
      salt = salt.b

      @cached_keys = Hash.new unless @cached_keys

      cached_key = @cached_keys[[password, salt]]
      return cached_key if cached_key

      iter = 2 * 1000 * 1000
      keylen = 32
      digest = OpenSSL::Digest.new 'sha256'

      key = OpenSSL::PKCS5.pbkdf2_hmac password.b, salt, iter, keylen, digest

      @cached_keys[[password, salt]] = key
      key
    end

    def self.generate_cipher_key
      SecureRandom.random_bytes 16
    end
  end
end