lib/lockbox/box.rb in lockbox-1.1.2 vs lib/lockbox/box.rb in lockbox-1.2.0

- old
+ new

@@ -1,8 +1,10 @@ module Lockbox class Box - def initialize(key: nil, algorithm: nil, encryption_key: nil, decryption_key: nil, padding: false) + NOT_SET = Object.new + + def initialize(key: nil, algorithm: nil, encryption_key: nil, decryption_key: nil, padding: false, associated_data: nil) raise ArgumentError, "Cannot pass both key and encryption/decryption key" if key && (encryption_key || decryption_key) key = Lockbox::Utils.decode_key(key) if key encryption_key = Lockbox::Utils.decode_key(encryption_key, size: 64) if encryption_key decryption_key = Lockbox::Utils.decode_key(decryption_key, size: 64) if decryption_key @@ -30,13 +32,15 @@ raise ArgumentError, "Unknown algorithm: #{algorithm}" end @algorithm = algorithm @padding = padding == true ? 16 : padding + @associated_data = associated_data end - def encrypt(message, associated_data: nil) + def encrypt(message, associated_data: NOT_SET) + associated_data = @associated_data if associated_data == NOT_SET message = Lockbox.pad(message, size: @padding) if @padding case @algorithm when "hybrid" raise ArgumentError, "No encryption key set" unless defined?(@encryption_box) raise ArgumentError, "Associated data not supported with this algorithm" if associated_data @@ -51,10 +55,11 @@ ciphertext = @box.encrypt(nonce, message, associated_data) end nonce + ciphertext end - def decrypt(ciphertext, associated_data: nil) + def decrypt(ciphertext, associated_data: NOT_SET) + associated_data = @associated_data if associated_data == NOT_SET message = case @algorithm when "hybrid" raise ArgumentError, "No decryption key set" unless defined?(@decryption_box) raise ArgumentError, "Associated data not supported with this algorithm" if associated_data