lib/lockbox/utils.rb in lockbox-0.2.5 vs lib/lockbox/utils.rb in lockbox-0.3.0
- old
+ new
@@ -1,6 +1,6 @@
-class Lockbox
+module Lockbox
class Utils
def self.build_box(context, options, table, attribute)
options = options.except(:attribute, :encrypted_attribute, :migrating, :attached, :type, :encode)
options.each do |k, v|
if v.is_a?(Proc)
@@ -19,14 +19,18 @@
def self.encrypted_options(record, name)
record.class.respond_to?(:lockbox_attachments) ? record.class.lockbox_attachments[name.to_sym] : nil
end
- def self.decode_key(key)
- if key.encoding != Encoding::BINARY && key =~ /\A[0-9a-f]{64,128}\z/i
+ def self.decode_key(key, size: 32)
+ if key.encoding != Encoding::BINARY && key =~ /\A[0-9a-f]{#{size * 2}}\z/i
key = [key].pack("H*")
end
+
+ raise Lockbox::Error, "Key must use binary encoding" if key.encoding != Encoding::BINARY
+ raise Lockbox::Error, "Key must be 32 bytes" if key.bytesize != size
+
key
end
def self.encrypted?(record, name)
!encrypted_options(record, name).nil?
@@ -35,27 +39,23 @@
def self.encrypt_attachable(record, name, attachable)
options = encrypted_options(record, name)
box = build_box(record, options, record.class.table_name, name)
case attachable
- when ActiveStorage::Blob
- raise NotImplementedError, "Not supported"
when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
attachable = {
- io: StringIO.new(box.encrypt(attachable.read)),
+ io: box.encrypt_io(attachable),
filename: attachable.original_filename,
content_type: attachable.content_type
}
when Hash
attachable = {
- io: StringIO.new(box.encrypt(attachable[:io].read)),
+ io: box.encrypt_io(attachable[:io]),
filename: attachable[:filename],
content_type: attachable[:content_type]
}
- when String
- raise NotImplementedError, "Not supported"
else
- nil
+ raise NotImplementedError, "Not supported"
end
attachable
end
end