Sha256: 309c62f03562a4f0e59f211f4765b35cf73578cc5190c8f3225d7689f909ff23

Contents?: true

Size: 920 Bytes

Versions: 55

Compression:

Stored size: 920 Bytes

Contents

# frozen_string_literal: true

require "openssl"

module Decidim
  # This class is used to generate secure tokens
  class Tokenizer
    #
    # Initializes the Tokenizer.
    #
    # salt      - The salt fr the encryption (it should be at leas 30 chars long)
    # length    - How long the key generated should be (in bytes)
    #
    def initialize(salt: nil, length: 32)
      @salt = salt.presence || Tokenizer.random_salt
      @length = length
    end

    def self.random_salt
      SecureRandom.hex(32)
    end

    attr_reader :salt, :length

    # returns a securely generated string of bytes
    def digest(string)
      OpenSSL::PKCS5.pbkdf2_hmac(string.to_s, salt, 20_000, length, "sha256")
    end

    def int_digest(string)
      digest(string.to_s).bytes.inject { |a, b| (a << 8) + b }
    end

    def hex_digest(string)
      digest(string.to_s).bytes.map { |c| c.ord.to_s(16) }.join
    end
  end
end

Version data entries

55 entries across 55 versions & 1 rubygems

Version Path
decidim-core-0.29.1 app/services/decidim/tokenizer.rb
decidim-core-0.28.4 app/services/decidim/tokenizer.rb
decidim-core-0.27.9 app/services/decidim/tokenizer.rb
decidim-core-0.29.0 app/services/decidim/tokenizer.rb
decidim-core-0.28.3 app/services/decidim/tokenizer.rb
decidim-core-0.27.8 app/services/decidim/tokenizer.rb
decidim-core-0.29.0.rc4 app/services/decidim/tokenizer.rb
decidim-core-0.29.0.rc3 app/services/decidim/tokenizer.rb
decidim-core-0.29.0.rc2 app/services/decidim/tokenizer.rb
decidim-core-0.29.0.rc1 app/services/decidim/tokenizer.rb
decidim-core-0.28.2 app/services/decidim/tokenizer.rb
decidim-core-0.27.7 app/services/decidim/tokenizer.rb
decidim-core-0.28.1 app/services/decidim/tokenizer.rb
decidim-core-0.27.6 app/services/decidim/tokenizer.rb
decidim-core-0.26.10 app/services/decidim/tokenizer.rb
decidim-core-0.26.9 app/services/decidim/tokenizer.rb
decidim-core-0.28.0 app/services/decidim/tokenizer.rb
decidim-core-0.27.5 app/services/decidim/tokenizer.rb
decidim-core-0.28.0.rc5 app/services/decidim/tokenizer.rb
decidim-core-0.28.0.rc4 app/services/decidim/tokenizer.rb