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

Gnupg Laravel Package

phpcq/gnupg

GnuPG wrapper and signature verification library used by the phpcq tool runner. Provides a lightweight API for interacting with GnuPG and validating signatures to support automated PHP code quality checks in CI pipelines.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require phpcq/gnupg
    

    Ensure the gnupg PHP extension is installed (pecl install gnupg or via system package manager).

  2. Basic Initialization in Laravel:

    use Phpcq\Gnupg\Gnupg;
    
    $gnupg = new Gnupg();
    $gnupg->setBinary(config('gnupg.binary_path', '/usr/bin/gpg')); // Configure in config/gnupg.php
    
  3. First Use Case: Verify a Git Commit Signature in CI

    $signature = file_get_contents(storage_path('app/signature.asc'));
    $commitData = file_get_contents(storage_path('app/commit.txt'));
    $fingerprint = config('gnupg.trusted_fingerprints.lead_developer');
    
    $result = $gnupg->verify($signature, $commitData, $fingerprint);
    
    if (!$result['valid']) {
        throw new \RuntimeException("Invalid commit signature: {$result['error']}");
    }
    
  4. Laravel Service Provider Setup (app/Providers/GnupgServiceProvider.php):

    use Illuminate\Support\ServiceProvider;
    use Phpcq\Gnupg\Gnupg;
    
    class GnupgServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton(Gnupg::class, function () {
                $gnupg = new Gnupg();
                $gnupg->setBinary(config('gnupg.binary_path'));
                return $gnupg;
            });
        }
    }
    
  5. Register the Provider (config/app.php):

    'providers' => [
        // ...
        App\Providers\GnupgServiceProvider::class,
    ],
    

Implementation Patterns

Core Usage Patterns

1. Signature Verification in CI/CD

use Illuminate\Support\Facades\Gnupg; // After creating a Facade

public function verifyCommitSignature()
{
    $signature = file_get_contents(storage_path('app/signature.asc'));
    $commitData = file_get_contents(storage_path('app/commit.txt'));
    $fingerprint = config('gnupg.trusted_fingerprints.lead_developer');

    $result = Gnupg::verify($signature, $commitData, $fingerprint);

    if (!$result['valid']) {
        event(new \App\Events\SignatureFailed($result['error']));
        return false;
    }

    return true;
}

2. Encrypting Sensitive Configuration

public function encryptConfig()
{
    $recipientFingerprint = config('gnupg.recipient_fingerprint');
    $sensitiveData = config('app.sensitive_data');

    $encrypted = Gnupg::encrypt($sensitiveData, $recipientFingerprint);
    file_put_contents(storage_path('app/encrypted_config.asc'), $encrypted);

    return true;
}

3. Decrypting Data in Deployment

public function decryptDeploymentData()
{
    $encryptedData = file_get_contents(storage_path('app/encrypted_data.asc'));
    $privateKey = file_get_contents(storage_path('app/private.key'));

    $decrypted = Gnupg::decrypt($encryptedData, $privateKey);
    return json_decode($decrypted, true);
}

4. Key Management

// Import a public key
Gnupg::importKey(file_get_contents(storage_path('app/public.key')));

// List all keys
$keys = Gnupg::listKeys();

Laravel-Specific Patterns

1. Facade for Cleaner Syntax

Create app/Facades/Gnupg.php:

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class Gnupg extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'gnupg';
    }
}

Update GnupgServiceProvider to bind the Facade:

$this->app->bind('gnupg', function () {
    return $this->app->make(Gnupg::class);
});

2. Artisan Commands for Key Management

use Illuminate\Console\Command;
use App\Facades\Gnupg;

class ImportGpgKey extends Command
{
    protected $signature = 'gpg:import {key_file}';
    protected $description = 'Import a GPG public key';

    public function handle()
    {
        $keyFile = $this->argument('key_file');
        $result = Gnupg::importKey(file_get_contents($keyFile));

        $this->info("Key imported: " . ($result ? 'Success' : 'Failed'));
    }
}

3. Middleware for API Signature Verification

use Closure;
use App\Facades\Gnupg;

class VerifyApiSignature
{
    public function handle($request, Closure $next)
    {
        $signature = $request->header('X-Signature');
        $data = $request->getContent();
        $fingerprint = config('gnupg.api_trusted_fingerprint');

        $result = Gnupg::verify($signature, $data, $fingerprint);

        if (!$result['valid']) {
            abort(403, 'Invalid signature');
        }

        return $next($request);
    }
}

4. Event Listeners for Signature Operations

use App\Facades\Gnupg;
use App\Events\SignatureVerified;

public function handle(SignatureVerified $event)
{
    // Log or notify on successful verification
    \Log::info("Signature verified for {$event->fingerprint}");
}

5. Caching Verification Results

use Illuminate\Support\Facades\Cache;

public function verifyWithCache($signature, $data, $fingerprint, $ttl = 3600)
{
    $cacheKey = "gpg_verify_{$fingerprint}_{md5($data)}";
    $cached = Cache::get($cacheKey);

    if ($cached !== null) {
        return $cached;
    }

    $result = Gnupg::verify($signature, $data, $fingerprint);
    Cache::put($cacheKey, $result, $ttl);

    return $result;
}

Gotchas and Tips

Pitfalls and Debugging

1. GnuPG Binary Path Issues

  • Problem: gpg command not found or incorrect path.
  • Fix: Explicitly set the binary path:
    $gnupg->setBinary('/usr/local/bin/gpg2'); // Use full path
    
  • Debug: Check with which gpg in your environment.

2. Key Fingerprint Mismatches

  • Problem: Verification fails due to incorrect fingerprint.
  • Fix: Use the exact fingerprint (e.g., gpg --list-keys to confirm).
  • Tip: Store fingerprints in config/gnupg.php:
    'trusted_fingerprints' => [
        'lead_developer' => 'ABCD1234EFGH5678',
    ],
    

3. Passphrase Handling

  • Problem: Encrypted keys require passphrases.
  • Fix: Use setPassphrase():
    $gnupg->setPassphrase(config('gnupg.private_key_passphrase'));
    
  • Security Tip: Store passphrases in Laravel Vault or AWS Secrets Manager, never in .env for production.

4. Large File Performance

  • Problem: Slow verification for large files (e.g., Git repos).
  • Fix: Stream data or use caching:
    $gnupg->setArmor(false); // Disable ASCII armor for binary data
    

5. Environment-Specific Issues

  • Problem: GnuPG not installed in Docker/CI.
  • Fix: Add to Dockerfile:
    RUN apt-get update && apt-get install -y gnupg
    
  • CI Tip: Use a setup script (e.g., scripts/install-gnupg.sh).

6. Signature Format Errors

  • Problem: gpg: no valid OpenPGP data found.
  • Fix: Ensure the signature file is in the correct format (ASCII armored or binary).
  • Debug: Verify with gpg --verify signature.asc file.txt.

7. Key Expiration

  • Problem: Expired keys cause verification failures.
  • Fix: Check key expiration with gpg --list-keys and update
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor