Class: Familia::Encryption::Manager
- Inherits:
-
Object
- Object
- Familia::Encryption::Manager
- Defined in:
- lib/familia/encryption/manager.rb
Overview
High-level encryption manager - replaces monolithic Encryption module
Instance Attribute Summary collapse
-
#provider ⇒ Object
readonly
Returns the value of attribute provider.
Instance Method Summary collapse
- #decrypt(encrypted_json_or_hash, context:, additional_data: nil) ⇒ Object
- #encrypt(plaintext, context:, additional_data: nil) ⇒ Object
-
#initialize(algorithm: nil) ⇒ Manager
constructor
A new instance of Manager.
Constructor Details
#initialize(algorithm: nil) ⇒ Manager
Returns a new instance of Manager.
11 12 13 14 15 |
# File 'lib/familia/encryption/manager.rb', line 11 def initialize(algorithm: nil) Registry.setup! if Registry.providers.empty? @provider = algorithm ? Registry.get(algorithm) : Registry.default_provider raise EncryptionError, 'No encryption provider available' unless @provider end |
Instance Attribute Details
#provider ⇒ Object (readonly)
Returns the value of attribute provider.
9 10 11 |
# File 'lib/familia/encryption/manager.rb', line 9 def provider @provider end |
Instance Method Details
#decrypt(encrypted_json_or_hash, context:, additional_data: nil) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/familia/encryption/manager.rb', line 39 def decrypt(encrypted_json_or_hash, context:, additional_data: nil) if encrypted_json_or_hash.nil? || (encrypted_json_or_hash.respond_to?(:empty?) && encrypted_json_or_hash.empty?) return nil end # Increment counter immediately to track all decryption attempts, even failed ones Familia::Encryption.derivation_count.increment data = parse_encrypted_data(encrypted_json_or_hash) # Validate algorithm support provider = Registry.get(data.algorithm) plaintext = decrypt_with_candidates(provider, data, context, additional_data) plaintext.force_encoding(data.encoding || 'UTF-8') rescue EncryptionError raise rescue Familia::SerializerError => e raise EncryptionError, "Invalid JSON structure: #{e.}" rescue StandardError => e raise EncryptionError, "Decryption failed: #{e.}" end |
#encrypt(plaintext, context:, additional_data: nil) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/familia/encryption/manager.rb', line 17 def encrypt(plaintext, context:, additional_data: nil) plaintext = plaintext.to_s return nil if plaintext.empty? key = derive_key(context) result = @provider.encrypt(plaintext, key, additional_data) encrypted_data = Familia::Encryption::EncryptedData.new( algorithm: @provider.algorithm, nonce: Base64.strict_encode64(result[:nonce]), ciphertext: Base64.strict_encode64(result[:ciphertext]), auth_tag: Base64.strict_encode64(result[:auth_tag]), key_version: current_key_version, encoding: plaintext.encoding.name, ).to_h Familia::JsonSerializer.dump(encrypted_data) ensure Familia::Encryption.secure_wipe(key) if key end |