Sha256: f74e5a7b3a3530e94e89c01de528fbebd6de16316ad382824d6269a23d391066

Contents?: true

Size: 1.19 KB

Versions: 11

Compression:

Stored size: 1.19 KB

Contents

module Lockbox
  class KeyGenerator
    def initialize(master_key)
      @master_key = master_key
    end

    # pattern ported from CipherSweet
    # https://ciphersweet.paragonie.com/internals/key-hierarchy
    def attribute_key(table:, attribute:)
      raise ArgumentError, "Missing table for key generation" if table.to_s.empty?
      raise ArgumentError, "Missing attribute for key generation" if attribute.to_s.empty?

      c = "\xB4"*32
      hkdf(Lockbox::Utils.decode_key(@master_key), salt: table.to_s, info: "#{c}#{attribute}", length: 32, hash: "sha384")
    end

    private

    def hash_hmac(hash, ikm, salt)
      OpenSSL::HMAC.digest(hash, salt, ikm)
    end

    def hkdf(ikm, salt:, info:, length:, hash:)
      if defined?(OpenSSL::KDF.hkdf)
        return OpenSSL::KDF.hkdf(ikm, salt: salt, info: info, length: length, hash: hash)
      end

      prk = hash_hmac(hash, ikm, salt)

      # empty binary string
      t = String.new
      last_block = String.new
      block_index = 1
      while t.bytesize < length
        last_block = hash_hmac(hash, last_block + info + [block_index].pack("C"), prk)
        t << last_block
        block_index += 1
      end

      t[0, length]
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
lockbox-0.4.2 lib/lockbox/key_generator.rb
lockbox-0.4.1 lib/lockbox/key_generator.rb
lockbox-0.4.0 lib/lockbox/key_generator.rb
lockbox-0.3.7 lib/lockbox/key_generator.rb
lockbox-0.3.6 lib/lockbox/key_generator.rb
lockbox-0.3.5 lib/lockbox/key_generator.rb
lockbox-0.3.4 lib/lockbox/key_generator.rb
lockbox-0.3.3 lib/lockbox/key_generator.rb
lockbox-0.3.2 lib/lockbox/key_generator.rb
lockbox-0.3.1 lib/lockbox/key_generator.rb
lockbox-0.3.0 lib/lockbox/key_generator.rb