lib/fernet/generator.rb in fernet-0.1 vs lib/fernet/generator.rb in fernet-1.0
- old
+ new
@@ -3,22 +3,32 @@
require 'openssl'
require 'date'
module Fernet
class Generator
- attr_accessor :data
+ attr_accessor :data, :payload
- def initialize(secret)
- @secret = secret
+ 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)
- mac = OpenSSL::HMAC.hexdigest('sha256', JSON.dump(data), secret)
- Base64.urlsafe_encode64(JSON.dump(data.merge(signature: mac)))
+ if encrypt?
+ iv = encrypt_data!
+ @payload = "#{base64(data)}|#{base64(iv)}"
+ else
+ @payload = base64(JSON.dump(data))
+ end
+
+ mac = OpenSSL::HMAC.hexdigest('sha256', payload, signing_key)
+ "#{payload}|#{mac}"
end
def inspect
"#<Fernet::Generator @secret=[masked] @data=#{@data.inspect}>"
end
@@ -28,7 +38,34 @@
@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(JSON.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