Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Eloquentencryption Laravel Package

richardstyles/eloquentencryption

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require richardstyles/eloquentencryption
    

    Publish the config file:

    php artisan vendor:publish --provider="RichardStyles\EloquentEncryption\EloquentEncryptionServiceProvider" --tag="config"
    
  2. Configure Encryption Key: Edit .env to specify your RSA private key path:

    ENCRYPTION_KEY_PATH=/path/to/private_key.pem
    

    Generate a 4096-bit RSA key pair if needed (e.g., using OpenSSL):

    openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:4096
    
  3. First Use Case: Encrypt a model attribute by adding $encrypted to the $fillable array:

    use RichardStyles\EloquentEncryption\EloquentEncryption;
    
    class User extends Model
    {
        use EloquentEncryption;
    
        protected $fillable = ['name', 'email', 'ssn']; // 'ssn' will be encrypted
    }
    

    Save a user instance:

    $user = new User(['ssn' => '123-45-6789']);
    $user->save(); // 'ssn' is automatically encrypted
    

Implementation Patterns

Workflows

  1. Encryption Scope:

    • Use $encrypted in $fillable to mark fields for encryption.
    • For dynamic encryption, override getEncryptedAttributes():
      protected function getEncryptedAttributes()
      {
          return ['ssn', 'credit_card']; // Dynamic list
      }
      
  2. Querying Encrypted Fields:

    • Encrypted fields are not searchable by default. Use raw queries for comparisons:
      $users = User::whereRaw("ssn = ?", [Encrypt::encrypt('123-45-6789')])->get();
      
  3. Key Rotation:

    • Rotate keys by updating ENCRYPTION_KEY_PATH in .env and re-encrypting data:
      php artisan eloquent-encryption:reencrypt
      
    • Schedule this during maintenance windows.
  4. Partial Encryption:

    • Encrypt only specific attributes during updates:
      $user->update(['ssn' => '987-65-4321'], ['encrypted' => ['ssn']]);
      

Integration Tips

  • API Responses: Automatically decrypt fields before JSON serialization by overriding toArray():

    public function toArray()
    {
        return array_merge(parent::toArray(), [
            'ssn' => $this->ssn, // Automatically decrypted
        ]);
    }
    
  • Form Requests: Use Encrypt::decrypt() in request validation:

    public function rules()
    {
        return [
            'ssn' => ['required', 'string', function ($attribute, $value, $fail) {
                if (!Encrypt::decrypt($value)) {
                    $fail('Invalid SSN format.');
                }
            }],
        ];
    }
    
  • Testing: Mock the encryption service in tests:

    $this->app->instance(Encrypt::class, Mockery::mock(Encrypt::class));
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Encryption/decryption adds ~5-10ms per field. Benchmark critical paths.
    • Avoid encrypting frequently queried fields (e.g., email for login).
  2. Key Management:

    • Never commit private keys to version control. Use environment variables or a secrets manager.
    • Backup keys securely; lost keys = lost data.
  3. Database Indexing:

    • Encrypted fields cannot be indexed. Use separate columns for searchable data if needed.
  4. PHP Extensions:

    • Requires openssl and sodium extensions. Verify with:
      php -m | grep -E 'openssl|sodium'
      
  5. Laravel Caching:

    • Encrypted attributes are not cached by default. Disable caching for models with encrypted fields:
      public $cache = false;
      

Debugging

  • Decryption Failures:

    • Check key permissions (chmod 600 private_key.pem).
    • Verify key format (PEM, not DER). Use:
      openssl rsa -in private_key.pem -check
      
  • Corrupted Data:

    • If decryption fails, the data may be corrupted. Re-encrypt the field manually:
      $user->ssn = Encrypt::encrypt($user->ssn);
      $user->save();
      
  • Logs: Enable debug mode in config/eloquent-encryption.php:

    'debug' => env('ENCRYPTION_DEBUG', false),
    

Extension Points

  1. Custom Encryption: Override the encryption service:

    $this->app->bind(Encrypt::class, function () {
        return new CustomEncryptService();
    });
    
  2. Attribute Whitelisting: Restrict encryption to specific models by extending the trait:

    abstract class EncryptableModel extends Model
    {
        use EloquentEncryption;
    
        public static function bootEncryptable()
        {
            static::addGlobalScope(new EncryptableScope);
        }
    }
    
  3. Batch Re-encryption: Extend the re-encryption command for large datasets:

    php artisan eloquent-encryption:reencrypt --model=User --chunk=1000
    
  4. Fallback for Missing Keys: Handle missing keys gracefully:

    try {
        $decrypted = Encrypt::decrypt($encryptedValue);
    } catch (KeyNotFoundException $e) {
        // Fallback logic (e.g., log or use default value)
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium