Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Node.js
node_modules/
.npm/
.yarn/

# Editor-specific
/.vscode/

# Generated files
.idx/

# Composer
vendor/
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## v0.1.0-alpha `2025-06-14`

Initial Alpha release. The package is functional, with documentation and unit tests included.

### Added

- Complete package scaffolding and setup.
- Database migration for encrypted data storage.
- Encryption table Eloquent model.
- Reusable trait for model property/attribute encryption.
- Core encryption controller.
- Comprehensive documentation, including installation and usage guides.
- Configuration file for package customization.
128 changes: 128 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
realstoman@gmail.com.
All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series
of actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.

Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
26 changes: 26 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Contributing

Thank you for considering to contribute to `laravel-db-encryption` 💖

We are always open for code improvements and features.

Please note that this project is released with a [Code of Conduct](https://github.com/wazzac/laravel-db-encryption/blob/main/CODE_OF_CONDUCT.md). By participating you agree to abide by its terms.

Since this package provides encryption features, please be mindful what data is written to the log file.

Lastly, for any new coding updates; please also include a unit test. Thank you 😉

## Setup

#### Fork this repo

[https://github.com/wazzac/laravel-db-encryption](https://github.com/wazzac/laravel-db-encryption)

#### Check the issues section if there are already issues and see if you can fix them


[https://github.com/wazzac/laravel-db-encryption/issues](https://github.com/wazzac/laravel-db-encryption/issues)

#### If the issue is new, add the code to the fork of the repository and then create a pull request.

#### Add Feat or Fix to the pull request title so maintainer understand what this issue is about.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2024 Warren Coetzee
Copyright (c) 2025 Warren Coetzee

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
119 changes: 117 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,117 @@
# laravel-db-encryption
A Laravel package that helps encrypt & decrypt certain defined table columns ensuring the data is secure in the database but can be accessed by the models.
# Laravel DB Encryptor

A Laravel package for secure, transparent encryption and decryption of sensitive model attributes, storing them in a dedicated table while keeping your main tables clean and fast.

## Features
- Seamless encryption/decryption of model attributes via a simple trait
- Encrypted data is stored in a separate `encrypted_attributes` table
- Only non-table attributes can be encrypted (enforced at runtime)
- Automatic loading and saving of encrypted attributes using Eloquent events
- **Search/filter on encrypted properties using SHA-256 hash**
- No sensitive values are ever logged
- Easy integration: just add the trait and define `$encryptedProperties` in your model
- Compatible with Laravel 9+

## Requirements
- PHP 8.1+
- Laravel 9 or higher
- OpenSSL PHP extension

## How It Works
1. Add the `HasEncryptedAttributes` trait to your Eloquent model.
2. Define a public array property `$encryptedProperties` listing the attributes you want encrypted (these must NOT exist as columns in the model's table).
3. When you load a model, encrypted attributes are automatically decrypted and available as normal properties.
4. When you save a model, encrypted attributes are removed from the main table and securely stored in the `encrypted_attributes` table.
5. **You can filter/search on encrypted properties using the provided query scope.**

**Example Model:**
```php
use Wazza\DbEncrypt\Traits\HasEncryptedAttributes;

class User extends Model
{
use HasEncryptedAttributes;

protected $fillable = ['name', 'email'];

// Only non-table attributes can be encrypted!
public array $encryptedProperties = [
'social_security_number',
'private_note',
];
}
```

## Usage
- Use your model as normal:
```php
$user = User::find(1);
$user->social_security_number = '123-45-6789';
$user->private_note = 'Sensitive info';
$user->save();

// When you retrieve the user again, encrypted attributes are automatically decrypted:
$user = User::find(1);
echo $user->social_security_number; // '123-45-6789'
```
- If you try to add an attribute to `$encryptedProperties` that already exists as a column, an exception will be thrown.

### Filtering/Search on Encrypted Properties
You can filter or search for models by encrypted property value using the built-in query scope:

```php
// Find users with a specific social security number
$users = User::whereEncrypted('social_security_number', '123-45-6789')->get();
```

This uses the SHA-256 hash of the value and joins the `encrypted_attributes` table for efficient searching, without ever exposing the decrypted value in the query or logs.

## Installation Steps
1. Require the package in your Laravel project:
```sh
composer require wazza/laravel-db-encryption
```
2. Publish the config and migration files (if needed):
```sh
php artisan vendor:publish --provider="Wazza\DbEncrypt\DbEncryptServiceProvider"
```
3. Run the migration to create the `encrypted_attributes` table:
```sh
php artisan migrate
```
4. Add the trait and `$encryptedProperties` to your models as shown above.

## Monitoring & Logs
- All encryption/decryption operations are logged (without sensitive values).
- To monitor package logs:
```sh
tail -f storage/logs/laravel.log | grep db-encrypt
```

## Testing
- Run the test suite using Pest:
```sh
./vendor/bin/pest

PASS Tests\Unit\EncryptorTest
✓ it correctly hashes the value 0.40s
✓ it correctly encrypts and decrypts data 0.15s
✓ it returns different ciphertext for same plaintext (random IV) 0.12s
✓ it throws on null input for encrypt 0.13s
✓ it throws on null input for decrypt 0.13s
✓ it throws on invalid base64 for decrypt 0.14s
✓ it throws on missing key in config 0.19s

PASS Tests\Unit\ExampleTest
✓ that true is true 0.28s

PASS Tests\Feature\ExampleTest
✓ it contains a successful example feature test 0.18s

Tests: 9 passed (9 assertions)
Duration: 1.98s
```
- Ensure your models and encrypted attributes behave as expected.

---
For more details, see the source code and comments. Contributions and issues welcome!
76 changes: 76 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"name": "wazza/laravel-db-encryption",
"description": "A Laravel package that helps encrypt & decrypt certain defined table columns ensuring the data is secure in the database but can be accessed by the models.",
"type": "library",
"keywords": [
"laravel",
"encryption",
"db-encryption",
"secure",
"package"
],
"homepage": "https://www.wazzac.dev",
"repository": "https://github.com/wazzac/laravel-db-encryption",
"readme": "README.md",
"require": {
"ext-json": "*",
"illuminate/support": "^12.0",
"php": "^8.2 || ^8.3"
},
"require-dev": {
"fakerphp/faker": "^1.20.0",
"laravel/legacy-factories": "~1",
"mockery/mockery": "^1.2",
"orchestra/testbench": "^10.0",
"pestphp/pest": "^3.8",
"pestphp/pest-plugin-laravel": "^3.2",
"phpunit/phpunit": "^11.0"
},
"license": "MIT",
"autoload": {
"psr-4": {
"Wazza\\DbEncrypt\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Wazza\\DbEncrypt\\": "src/",
"Wazza\\DbEncrypt\\Tests\\": "tests/",
"Wazza\\DbEncrypt\\Database\\Factories\\": "database/factories/",
"Wazza\\DbEncrypt\\Database\\Seeders\\": "database/seeders/"
}
},
"extra": {
"laravel": {
"providers": [
"Wazza\\DbEncrypt\\Providers\\DbEncryptServiceProvider"
],
"aliases": {
"DbEncrypt": "Wazza\\DbEncrypt\\Facades\\DbEncrypt"
}
}
},
"authors": [
{
"name": "Warren Coetzee",
"email": "warren.coetzee@gmail.com",
"homepage": "https://www.wazzac.dev"
}
],
"support": {
"issues": "https://github.com/wazzacdev/laravel-db-encryption/issues",
"source": "https://github.com/wazzacdev/laravel-db-encryption"
},
"scripts": {
"post-autoload-dump": [
"@php ./vendor/bin/testbench package:discover --ansi"
]
},
"minimum-stability": "stable",
"prefer-stable": true,
"config": {
"allow-plugins": {
"pestphp/pest-plugin": true
}
}
}
Loading