Sha256: 191c900c5346f9f016af1bd337bfc5176dced9f4f9a4c832218e604c334d79da

Contents?: true

Size: 1.35 KB

Versions: 1

Compression:

Stored size: 1.35 KB

Contents

require 'base64'
require 'multi_json'
require 'openssl'
require 'date'

module Fernet::Legacy
  class Generator
    attr_accessor :data, :payload

    def initialize(secret, encrypt)
      @secret  = Secret.new(secret, encrypt)
      @encrypt = encrypt
      @payload = ''
      @data    = {}
    end

    def generate
      yield self if block_given?
      data.merge!(:issued_at => DateTime.now)

      if encrypt?
        iv = encrypt_data!
        @payload = "#{base64(data)}|#{base64(iv)}"
      else
        @payload = base64(MultiJson.dump(data))
      end

      mac = OpenSSL::HMAC.hexdigest('sha256', payload, signing_key)
      "#{payload}|#{mac}"
    end

    def inspect
      "#<Fernet::Legacy::Generator @secret=[masked] @data=#{@data.inspect}>"
    end
    alias to_s inspect

    def data
      @data ||= {}
    end

  private
    attr_reader :secret

    def encrypt_data!
      cipher = OpenSSL::Cipher.new('AES-128-CBC')
      cipher.encrypt
      iv         = cipher.random_iv
      cipher.iv  = iv
      cipher.key = encryption_key[0, 16]
      @data = cipher.update(MultiJson.dump(data)) + cipher.final
      iv
    end

    def base64(chars)
      Base64.urlsafe_encode64(chars)
    end

    def encryption_key
      @secret.encryption_key
    end

    def signing_key
      @secret.signing_key
    end

    def encrypt?
      @encrypt
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
legacy-fernet-1.6.4 lib/fernet/legacy/generator.rb