lib/fernet/generator.rb in fernet-1.6 vs lib/fernet/generator.rb in fernet-2.0.rc1
- old
+ new
@@ -1,71 +1,37 @@
+#encoding UTF-8
require 'base64'
-require 'yajl'
require 'openssl'
require 'date'
module Fernet
class Generator
- attr_accessor :data, :payload
+ attr_accessor :message
- def initialize(secret, encrypt)
- @secret = Secret.new(secret, encrypt)
- @encrypt = encrypt
- @payload = ''
- @data = {}
+ def initialize(opts)
+ @secret = opts.fetch(:secret)
+ @message = opts[:message]
+ @iv = opts[:iv]
+ @now = opts[:now]
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}"
+ token = Token.generate(secret: @secret,
+ message: @message,
+ iv: @iv,
+ now: @now)
+ token.to_s
end
def inspect
- "#<Fernet::Generator @secret=[masked] @data=#{@data.inspect}>"
+ "#<Fernet::Generator @secret=[masked] @message=#{@message.inspect}>"
end
alias to_s inspect
- def data
- @data ||= {}
+ def data=(message)
+ puts "[WARNING] 'data' is deprecated, use 'message' instead"
+ @message = message
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