Sha256: fa45241cd49ce76bab7474052fd13eaf29d7731eb816c20b0c46240d3774869d

Contents?: true

Size: 1.33 KB

Versions: 5

Compression:

Stored size: 1.33 KB

Contents

require 'base64'
require 'yajl'
require 'openssl'
require 'date'

module Fernet
  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(Yajl::Encoder.encode(data))
      end

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

    def inspect
      "#<Fernet::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
      @data = cipher.update(Yajl::Encoder.encode(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

5 entries across 5 versions & 1 rubygems

Version Path
fernet-1.6 lib/fernet/generator.rb
fernet-1.4 lib/fernet/generator.rb
fernet-1.3 lib/fernet/generator.rb
fernet-1.2 lib/fernet/generator.rb
fernet-1.1 lib/fernet/generator.rb