PHPackages                             securecrypto/laravel-encryption - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. securecrypto/laravel-encryption

ActiveLibrary[API Development](/categories/api)

securecrypto/laravel-encryption
===============================

Professional Laravel package for secure encryption with Strategy Pattern, SOLID principles, and modern PHP 8.2+ features

v1.5.0(today)01↑2900%MITPHPPHP ^8.2CI failing

Since Jun 17Pushed todayCompare

[ Source](https://github.com/sanjeevturkauli/crypt)[ Packagist](https://packagist.org/packages/securecrypto/laravel-encryption)[ RSS](/packages/securecrypto-laravel-encryption/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (6)Versions (7)Used By (0)

SecureCrypto - Laravel Encryption Package 🔐
===========================================

[](#securecrypto---laravel-encryption-package-)

[![Latest Version](https://camo.githubusercontent.com/af8173b14f80fda63a00d698b31657ae96f82b78c5a2f43ca27ba0c47bdad318/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73656375726563727970746f2f6c61726176656c2d656e6372797074696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/securecrypto/laravel-encryption)[![License](https://camo.githubusercontent.com/33eb1aff97ef4cf63df04d4687b216520a4c701c0ff570b3a11b72ef2ad993ef/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73656375726563727970746f2f6c61726176656c2d656e6372797074696f6e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/f0321e3ba46e712d07b9eb361cb92d327f94e60b1eb34f960caa204001b123e1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f73656375726563727970746f2f6c61726176656c2d656e6372797074696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/securecrypto/laravel-encryption)

Enterprise-grade Laravel package for automatic API request/response encryption and decryption. Built with modern design patterns, SOLID principles, and PHP 8.2+ features.

**Perfect for mobile apps with hex encoding, auto-generated keys, and enterprise-ready architecture!**

### 🏆 Professional Features

[](#-professional-features)

- ✅ **Strategy Pattern** - Pluggable encryption drivers
- ✅ **SOLID Principles** - Clean, maintainable code
- ✅ **Auto-Generated Keys** - Zero configuration
- ✅ **Mobile Compatible** - Hex encoding support
- ✅ **Customizable Response** - Configure your own response structure
- ✅ **Request Control** - Disable encryption via headers/params
- ✅ **Security Hardened** - Code integrity verification
- ✅ **Type-Safe** - Full PHP 8.2+ type hints
- ✅ **Well-Tested** - Comprehensive test coverage

---

🚀 Quick Start (3 Steps)
-----------------------

[](#-quick-start-3-steps)

**Step 1: Install**

```
composer require securecrypto/laravel-encryption
```

✅ Keys auto-generated in `.env`!

**Step 2: Publish Config**

```
php artisan vendor:publish --tag=secure-crypto-config
```

**Step 3: Use in Routes**

```
$middlewares = env('RESPONSE_CRYPT_ENABLED', false)
    ? ['request.decrypt', 'response.encrypt']
    : [];

Route::middleware($middlewares)->group(function () {
    // Your encrypted routes here
});
```

**Enable in `.env`:**

```
RESPONSE_CRYPT_ENABLED=true
```

**Done! 🎉** [Full Installation Guide →](INSTALLATION.md)

---

✨ Features
----------

[](#-features)

### 🎯 Core Features

[](#-core-features)

✅ **Auto-Generate Keys** - Encryption keys created on install
✅ **Strategy Pattern** - Pluggable encryption drivers (Hex, OpenSSL, Laravel)
✅ **Zero Configuration** - Works out of the box
✅ **Middleware Based** - Automatic request/response handling
✅ **Mobile Compatible** - Hex encoding for mobile apps

### 🏗️ Architecture

[](#️-architecture)

✅ **Design Patterns** - Strategy, Facade, Dependency Injection
✅ **SOLID Principles** - Professional, maintainable code
✅ **Interface-Based** - Easy to extend with custom drivers
✅ **Type-Safe** - Full PHP 8.2+ type hints
✅ **Modern PHP** - match(), named parameters, strict types

### ⚙️ Configuration

[](#️-configuration)

✅ **Route Exclusions** - Skip encryption for specific routes
✅ **Key Exclusions** - Exclude response keys from encryption
✅ **Flexible Drivers** - Switch between Hex, OpenSSL, Laravel Crypt
✅ **Environment Control** - Easy enable/disable via `.env`

### 🛠️ Developer Experience

[](#️-developer-experience)

✅ **Helper Functions** - `encrypt_data()`, `decrypt_data()`
✅ **Facade Support** - Clean API: `ResponseCrypt::encrypt()`
✅ **Command Tools** - `php artisan crypt:keys`
✅ **Laravel 10-13** - Full compatibility

📋 Requirements
--------------

[](#-requirements)

- PHP 8.2 or higher
- Laravel 10.x, 11.x, 12.x, or 13.x

---

📦 Installation
--------------

[](#-installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require securecrypto/laravel-encryption
```

✅ **Keys are automatically generated** and added to your `.env` file!

### Step 2: Publish Configuration

[](#step-2-publish-configuration)

```
php artisan vendor:publish --tag=secure-crypto-config
```

This creates `config/crypt.php` in your application.

### Step 3: Check Auto-Generated Keys

[](#step-3-check-auto-generated-keys)

After installation, check your `.env` file. You'll see:

```
# Response Crypt Package - Auto-generated Keys
RESPONSE_CRYPT_KEY="oJh92F4FPq7xE3+mvVuEXA=="
RESPONSE_CRYPT_IV="mWnVJb8mZ3hXjx9P9F2pG6F8ZT6Pb9vh+bDqWzTVkMg="
```

**These are automatically created on package installation!** You can customize them if needed.

### Step 4: Generate New Keys (Optional)

[](#step-4-generate-new-keys-optional)

If you want to regenerate keys:

```
# Generate and save to .env
php artisan crypt:keys

# Show keys without saving
php artisan crypt:keys --show

# Force in production
php artisan crypt:keys --force
```

**Beautiful Console Output:**

```
$ php artisan crypt:keys

   INFO  Encryption keys generated successfully!

  ✓ RESPONSE_CRYPT_KEY ........................... oJh92F4FPq7xE3+mv...
  ✓ RESPONSE_CRYPT_IV ............................ mWnVJb8mZ3hXjx9P9...

  ✓ Keys added to .env file

```

---

⚙️ Configuration
----------------

[](#️-configuration-1)

### Environment Variables

[](#environment-variables)

```
# Enable/Disable encryption
RESPONSE_CRYPT_ENABLED=true

# Encryption driver
# Options: hex, openssl_fixed, openssl, laravel
RESPONSE_CRYPT_DRIVER=hex

# Auto-generated keys (or set custom ones)
RESPONSE_CRYPT_KEY="your-key-here"
RESPONSE_CRYPT_IV="your-iv-here"

# Optional: Enable logging
RESPONSE_CRYPT_LOG_ENABLED=false
```

### Encryption Drivers (Strategy Pattern)

[](#encryption-drivers-strategy-pattern)

The package uses **Strategy Design Pattern** for flexible encryption:

DriverEncodingIVImplementationBest For`hex`HexadecimalFixed`HexEncryptionDriver`**Mobile Apps** 📱`openssl_fixed`Base64Fixed`OpenSSLDriver`Web apps with fixed IV`openssl`Base64Random`OpenSSLDriver`**Max Security** 🔒`laravel`Base64Random`LaravelEncryptionDriver`Simple projects**Default: `hex`** - Perfect for mobile compatibility!

**Want custom encryption?** Just implement `EncryptionDriverInterface`!

### Config File Options

[](#config-file-options)

The `config/crypt.php` file offers extensive customization:

```
return [
    // Enable/disable encryption globally
    'enabled' => env('RESPONSE_CRYPT_ENABLED', true),

    // Encryption driver: hex, openssl_fixed, openssl, laravel
    'driver' => env('RESPONSE_CRYPT_DRIVER', 'hex'),

    // Encryption key (auto-generated on install)
    'key' => env('RESPONSE_CRYPT_KEY'),

    // Encryption IV (auto-generated on install)
    'iv' => env('RESPONSE_CRYPT_IV'),

    // Enable response encryption
    'encrypt_response' => true,

    // Enable request decryption
    'decrypt_request' => true,

    // Response wrapper key
    'response_wrapper_key' => 'payload',

    // Request payload key
    'request_payload_key' => 'payload',

    // Include metadata in response
    'include_meta' => true,

    // Routes to exclude from encryption
    'excluded_routes' => [
        'login',
        'register',
        'sanctum/csrf-cookie',
        'health',
    ],

    // Response keys to exclude from encryption
    'excluded_keys' => [
        'token_type',
        'expires_in',
    ],

    // Cipher algorithm
    'cipher' => 'AES-256-CBC',
];
```

---

💻 Usage
-------

[](#-usage)

### Basic Route Middleware

[](#basic-route-middleware)

**Simple Enable/Disable Pattern (Recommended):**

```
use Illuminate\Support\Facades\Route;

// Enable/disable encryption with environment variable
$middlewares = env('RESPONSE_CRYPT_ENABLED', false)
    ? ['request.decrypt', 'response.encrypt']
    : [];

Route::middleware($middlewares)->group(function () {
    // All your API routes here
    Route::post('/login', [AuthController::class, 'login']);
    Route::get('/users', [UserController::class, 'index']);
    Route::post('/posts', [PostController::class, 'store']);
});
```

### Middleware Options

[](#middleware-options)

MiddlewareAliasDescription`EncryptApiResponse``response.encrypt`Encrypts outgoing responses only`DecryptApiRequest``request.decrypt`Decrypts incoming requests only`EncryptDecryptApi``api.crypt`Both encrypt response and decrypt request**Example Usage:**

```
// Only encrypt responses
Route::middleware(['response.encrypt'])->get('/api/data', function () {
    return response()->json(['message' => 'This will be encrypted']);
});

// Only decrypt requests
Route::middleware(['request.decrypt'])->post('/api/process', function () {
    return response()->json(['received' => request()->all()]);
});

// Both encrypt and decrypt
Route::middleware(['api.crypt'])->post('/api/secure', function () {
    return response()->json([
        'status' => true,
        'data' => request()->all()
    ]);
});
```

### Using Facade

[](#using-facade)

```
use Sanjeev\ResponseCrypt\Facades\ResponseCrypt;

// Encrypt data
$encrypted = ResponseCrypt::encrypt(['secret' => 'data', 'key' => 'value']);

// Decrypt data
$decrypted = ResponseCrypt::decrypt($encrypted);

// Encrypt array for response
$response = ResponseCrypt::encryptArray(['status' => true, 'data' => $data]);

// Decrypt request array
$data = ResponseCrypt::decryptArray($request->all());
```

### Helper Functions

[](#helper-functions)

```
// Encrypt data
$encrypted = encrypt_data(['name' => 'John', 'email' => 'john@example.com']);

// Decrypt data
$decrypted = decrypt_data($encrypted);

// Encrypt for response
$response = encrypt_response(['status' => true, 'message' => 'Success']);

// Decrypt request
$data = decrypt_request($request->all());
```

---

🔄 Migration from Existing Setup
-------------------------------

[](#-migration-from-existing-setup)

If you have an existing encryption implementation like this:

```
// Old way
$middlewares = env('IS_ENCRYPTION', false)
    ? ['decrypt.request', 'encrypt.response']
    : [];
```

**Simply change to:**

```
// New way with Response Crypt
$middlewares = env('RESPONSE_CRYPT_ENABLED', false)
    ? ['request.decrypt', 'response.encrypt']
    : [];
```

**And update `.env`:**

```
# Old
IS_ENCRYPTION=true
ENCRYPTION_KEY="..."
ENCRYPTION_IV="..."

# New (keys auto-generated on install)
RESPONSE_CRYPT_ENABLED=true
RESPONSE_CRYPT_KEY="auto-generated"
RESPONSE_CRYPT_IV="auto-generated"
RESPONSE_CRYPT_DRIVER=hex
```

**✅ That's it! Your mobile app will continue working without any changes!**

---

📱 Mobile App Compatibility
--------------------------

[](#-mobile-app-compatibility)

### Hex Encoding (Default)

[](#hex-encoding-default)

The package uses **hex encoding by default** (`driver=hex`), which is:

- ✅ Compatible with most mobile apps
- ✅ Compatible with existing implementations
- ✅ No changes needed in your mobile app code

### Request Format

[](#request-format)

**Send encrypted request:**

```
{
  "payload": "3a4b5c6d7e8f9a0b1c2d3e4f..."
}
```

**The server will automatically decrypt it!**

### Response Format

[](#response-format)

**Server encrypts response:**

```
{
  "encrypted": true,
  "payload": "1a2b3c4d5e6f7a8b9c0d1e2f...",
  "meta": {
    "algorithm": "hex",
    "timestamp": "2024-06-18T10:30:00Z"
  }
}
```

**Your mobile app decrypts the `payload` field.**

---

🎯 Complete Example
------------------

[](#-complete-example)

**File: `routes/api.php`**

```
