PHPackages                             jjoek/laravel-hybrid-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. jjoek/laravel-hybrid-encryption

ActiveLibrary[API Development](/categories/api)

jjoek/laravel-hybrid-encryption
===============================

Laravel package for hybrid encryption (RSA-OAEP + AES-256-GCM) for secure API request handling

v1.1.0(3mo ago)02↓90%MITPHPPHP ^8.1

Since Apr 2Pushed 3mo agoCompare

[ Source](https://github.com/jjoek/laravel-hybrid-encryption)[ Packagist](https://packagist.org/packages/jjoek/laravel-hybrid-encryption)[ RSS](/packages/jjoek-laravel-hybrid-encryption/feed)WikiDiscussions main Synced 4w ago

READMEChangelogDependencies (5)Versions (3)Used By (0)

Laravel Hybrid Encryption
=========================

[](#laravel-hybrid-encryption)

A Laravel package for hybrid encryption using RSA-OAEP + AES-256-GCM for secure API request handling.

Features
--------

[](#features)

- **Hybrid Encryption**: Combines RSA-OAEP for key exchange with AES-256-GCM for data encryption
- **Automatic Request Decryption**: Middleware automatically decrypts encrypted requests
- **Public Key Endpoint**: Built-in endpoint to expose your public key to frontend clients
- **Secure by Default**: Uses industry-standard encryption algorithms

Installation
------------

[](#installation)

### From Packagist

[](#from-packagist)

```
composer require jjoek/laravel-hybrid-encryption
```

Configuration
-------------

[](#configuration)

### 1. Generate RSA Key Pair

[](#1-generate-rsa-key-pair)

```
# Generate private key (2048 or 4096 bits)
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048

# Extract public key
openssl rsa -pubout -in private_key.pem -out public_key.pem
```

### 2. Add Keys to Environment

[](#2-add-keys-to-environment)

Add to your `.env` file (replace newlines with `\n`):

```
ENCRYPTION_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBg...\n-----END PRIVATE KEY-----"
ENCRYPTION_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkq...\n-----END PUBLIC KEY-----"
```

**Tip**: Use this command to format your key for `.env`:

```
cat private_key.pem | tr '\n' '\\' | sed 's/\\/\\n/g'
```

### 3. Publish Configuration (Optional)

[](#3-publish-configuration-optional)

```
php artisan vendor:publish --tag=hybrid-encryption-config
```

Usage
-----

[](#usage)

### Public Key Endpoint

[](#public-key-endpoint)

The package automatically registers a public key endpoint:

```
GET /api/v1/public-key

```

Response:

```
{
    "publicKey": "-----BEGIN PUBLIC KEY-----\n...",
    "algorithm": "RSA-OAEP+AES-GCM-256",
    "keyFormat": "PEM"
}
```

### Decrypting Requests

[](#decrypting-requests)

Add the middleware to routes that should accept encrypted requests:

```
// routes/api.php
Route::post('/endpoint', ServiceController::class)
    ->middleware('decrypt.request');
```

### Expected Request Format

[](#expected-request-format)

Frontend sends encrypted data with these headers:

```
X-Encrypted: true
X-Encryption-Algorithm: RSA-OAEP+AES-GCM-256

```

Request body:

```
{
    "encryptedKey": "",
    "encryptedData": "",
    "iv": ""
}
```

### Using the Facade

[](#using-the-facade)

```
use Jjoek\HybridEncryption\Facades\HybridEncryption;

// Get public key
$publicKey = HybridEncryption::getPublicKey();

// Check if encryption is configured
if (HybridEncryption::isConfigured()) {
    // Manually decrypt data
    $decrypted = HybridEncryption::decrypt($encryptedPayload);
}
```

Configuration Options
---------------------

[](#configuration-options)

```
// config/hybrid-encryption.php

return [
    // RSA private key (PEM format)
    'private_key' => env('ENCRYPTION_PRIVATE_KEY'),

    // RSA public key (PEM format)
    'public_key' => env('ENCRYPTION_PUBLIC_KEY'),

    // Route configuration
    'route' => [
        'enabled' => true,           // Enable/disable the public key route
        'prefix' => 'api/v1',        // Route prefix
        'path' => 'public-key',      // Route path
        'middleware' => ['api'],     // Applied middleware
        'name' => 'hybrid-encryption.public-key',
    ],

    // Middleware alias name
    'middleware_alias' => 'decrypt.request',
];
```

Frontend Implementation (JavaScript)
------------------------------------

[](#frontend-implementation-javascript)

```
async function encryptPayload(data, publicKeyPem) {
    // Import the public key
    const publicKey = await crypto.subtle.importKey(
        'spki',
        pemToArrayBuffer(publicKeyPem),
        { name: 'RSA-OAEP', hash: 'SHA-256' },
        false,
        ['encrypt']
    );

    // Generate random AES key and IV
    const aesKey = await crypto.subtle.generateKey(
        { name: 'AES-GCM', length: 256 },
        true,
        ['encrypt']
    );
    const iv = crypto.getRandomValues(new Uint8Array(12));

    // Encrypt the data with AES-GCM
    const encodedData = new TextEncoder().encode(JSON.stringify(data));
    const encryptedData = await crypto.subtle.encrypt(
        { name: 'AES-GCM', iv },
        aesKey,
        encodedData
    );

    // Encrypt the AES key with RSA-OAEP
    const rawAesKey = await crypto.subtle.exportKey('raw', aesKey);
    const encryptedKey = await crypto.subtle.encrypt(
        { name: 'RSA-OAEP' },
        publicKey,
        rawAesKey
    );

    return {
        encryptedKey: arrayBufferToBase64(encryptedKey),
        encryptedData: arrayBufferToBase64(encryptedData),
        iv: arrayBufferToBase64(iv)
    };
}
```

Security Considerations
-----------------------

[](#security-considerations)

- **Never expose the private key** - Keep it secure in environment variables or a secrets manager
- **Use HTTPS** - Always use TLS in production to protect the encrypted payload in transit
- **Key Rotation** - Implement a key rotation strategy for production environments
- **Key Size** - Use at least 2048-bit RSA keys; 4096-bit recommended for sensitive applications

License
-------

[](#license)

MIT License

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance82

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

90d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b309aa7d384639628fa18f41e1bfe0a420343c9e632f9fd1a56f485f2de7c727?d=identicon)[jjoek](/maintainers/jjoek)

---

Top Contributors

[![jjoek](https://avatars.githubusercontent.com/u/35167093?v=4)](https://github.com/jjoek "jjoek (2 commits)")

---

Tags

apilaravelsecurityencryptionrsaaeshybrid-encryption

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jjoek-laravel-hybrid-encryption/health.svg)

```
[![Health](https://phpackages.com/badges/jjoek-laravel-hybrid-encryption/health.svg)](https://phpackages.com/packages/jjoek-laravel-hybrid-encryption)
```

###  Alternatives

[laravel/socialite

Laravel wrapper around OAuth 1 &amp; OAuth 2 libraries.

5.7k108.5M864](/packages/laravel-socialite)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M345](/packages/psalm-plugin-laravel)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

815320.5k3](/packages/defstudio-telegraph)[resend/resend-laravel

Resend for Laravel

1222.7M8](/packages/resend-resend-laravel)[essa/api-tool-kit

set of tools to build an api with laravel

53386.5k](/packages/essa-api-tool-kit)[api-platform/laravel

API Platform support for Laravel

59156.3k11](/packages/api-platform-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
