Weave 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

phar-io/gnupg

PHP wrapper for GnuPG used by phar-io tools, providing a simple API to verify and manage PGP signatures in PHP. Helps integrate GPG key handling and signature checks into builds and distribution workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require phar-io/gnupg
    

    Ensure the gnupg binary is installed on your system (Linux: sudo apt-get install gnupg, macOS: brew install gnupg).

  2. Basic Initialization

    use PharIo\Gnupg\Gnupg;
    
    $gpg = new Gnupg([
        'binary' => '/usr/bin/gpg', // Path to GPG binary (adjust if needed)
        'options' => [
            Gnupg::OPT_NO_VERIFY,
            Gnupg::OPT_NO_DEFAULT_KEYRING,
        ],
    ]);
    
  3. First Use Case: Encrypting a Message

    $recipientKey = '-----BEGIN PGP PUBLIC KEY BLOCK-----...';
    $gpg->addKey($recipientKey);
    
    $encrypted = $gpg->encrypt('Hello, world!');
    echo $encrypted; // Outputs armored PGP message
    

Implementation Patterns

Key Management Workflows

  • Importing Keys

    $gpg->addKey(file_get_contents('public.key'));
    $gpg->addSecretKey(file_get_contents('private.key'), 'passphrase');
    

    Tip: Use Laravel’s Storage facade to fetch keys from disk or cloud storage.

  • Signing and Verifying

    // Sign
    $signed = $gpg->sign('message', 'private-key-id');
    // Verify
    $verified = $gpg->verify($signed);
    

Integration with Laravel

  • Service Provider Binding

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Gnupg::class, function ($app) {
            return new Gnupg([
                'binary' => config('gnupg.binary'),
                'options' => [Gnupg::OPT_ARMOR],
            ]);
        });
    }
    
  • Configurable GPG Options

    // config/gnupg.php
    return [
        'binary' => env('GPG_BINARY', '/usr/bin/gpg'),
        'options' => [
            Gnupg::OPT_ARMOR,
            Gnupg::OPT_NO_VERIFY,
        ],
    ];
    

Common Use Cases

  1. Email Encryption Use with Laravel’s Mail facade to encrypt email bodies before sending.

    $encrypted = $gpg->encrypt($emailBody);
    Mail::send([...], function ($message) use ($encrypted) {
        $message->setBody($encrypted);
    });
    
  2. Secure API Responses Encrypt sensitive data in API responses using middleware.

    // app/Http/Middleware/EncryptResponse.php
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if ($response->isJson() && $request->hasValidToken()) {
            $encrypted = $gpg->encrypt($response->getContent());
            $response->setContent($encrypted);
        }
        return $response;
    }
    

Gotchas and Tips

Pitfalls

  1. Binary Path Issues

    • Problem: GnuPGException if the GPG binary isn’t found.
    • Fix: Explicitly set the binary path in config or use which gpg to locate it dynamically.
      $binaryPath = shell_exec('which gpg');
      $gpg = new Gnupg(['binary' => trim($binaryPath)]);
      
  2. Keyring Permissions

    • Problem: GPG may fail silently if the keyring lacks read/write permissions.
    • Fix: Ensure the user running PHP has access to ~/.gnupg/ or specify a custom keyring.
      $gpg = new Gnupg([
          'options' => [Gnupg::OPT_KEYRING => '/custom/path/keyring.gpg'],
      ]);
      
  3. Passphrase Handling

    • Problem: Hardcoding passphrases in code is insecure.
    • Fix: Use Laravel’s env() or a secrets manager (e.g., AWS Secrets Manager).
      $gpg->addSecretKey($privateKey, env('GPG_PRIVATE_KEY_PASSPHRASE'));
      

Debugging

  • Enable Verbose Output

    $gpg = new Gnupg(['options' => [Gnupg::OPT_VERBOSE]]);
    

    Check logs for GPG command execution details.

  • Validate Armored Output Ensure Gnupg::OPT_ARMOR is set when working with ASCII-armored messages (e.g., for email).

Extension Points

  1. Custom GPG Commands Use the exec() method for unsupported operations:

    $output = $gpg->exec('list-keys');
    
  2. Event Listeners Extend the class to log operations or trigger events:

    $gpg = new class extends Gnupg {
        public function encrypt($message, $recipient) {
            \Log::debug("Encrypting for: $recipient");
            return parent::encrypt($message, $recipient);
        }
    };
    
  3. Fallback for Missing Binary Implement a fallback (e.g., PHP-GPG) if gnupg is unavailable:

    try {
        $gpg = new Gnupg([...]);
    } catch (\PharIo\Gnupg\Exception\GnuPGException $e) {
        $gpg = new FallbackGpgWrapper();
    }
    
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.
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource