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

Pki Framework Laravel Package

spomky-labs/pki-framework

PHP 8.1+ framework for Public Key Infrastructure: X.509 certificates (incl. attribute certs), ASN.1 DER encoding/decoding, X.501/X.520 DN parsing, PEM (RFC 7468) handling, and PKCS-oriented cryptography utilities.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spomky-labs/pki-framework
    

    Ensure gmp or bcmath extensions are enabled for cryptographic operations.

  2. First Use Case: Certificate Creation

    use SpomkyLabs\PkiFramework\Certificate\Certificate;
    use SpomkyLabs\PkiFramework\Certificate\CertificateSubject;
    use SpomkyLabs\PkiFramework\Certificate\CertificateIssuer;
    use SpomkyLabs\PkiFramework\Certificate\CertificatePublicKey;
    use SpomkyLabs\PkiFramework\Certificate\CertificateValidity;
    use SpomkyLabs\PkiFramework\Certificate\CertificateExtensions;
    
    // Generate a private key (simplified example)
    $privateKey = openssl_pkey_new(['digest_alg' => 'sha256']);
    
    // Create a certificate
    $certificate = new Certificate(
        new CertificateSubject('CN=example.com'),
        new CertificateIssuer('CN=Root CA'),
        new CertificatePublicKey(openssl_pkey_get_details($privateKey)['key']),
        new CertificateValidity(
            new \DateTimeImmutable('-1 year'),
            new \DateTimeImmutable('+1 year')
        ),
        new CertificateExtensions()
    );
    
    // Sign the certificate (simplified; requires a CA private key)
    $certificate->sign($caPrivateKey);
    $pem = $certificate->toPem();
    
  3. First Use Case: Certificate Validation

    use SpomkyLabs\PkiFramework\Certificate\CertificateFactory;
    
    $certificate = CertificateFactory::fromPem($pem);
    $isValid = $certificate->isValid(new \DateTimeImmutable());
    

Where to Look First

  • Documentation: Start with the Certificate, CertificateFactory, and CertificateValidator classes.
  • Examples: Practical use cases like certificate generation, validation, and ASN.1 parsing.
  • Tests: Real-world scenarios for edge cases (e.g., expired certificates, custom extensions).

Implementation Patterns

Core Workflows

1. Certificate Issuance

  • Pattern: Use CertificateFactory to create and sign certificates programmatically.
    $factory = new CertificateFactory();
    $certificate = $factory->createCertificate(
        $subject,
        $issuer,
        $publicKey,
        $validity,
        $extensions,
        $signatureAlgorithm
    );
    $certificate->sign($caPrivateKey);
    
  • Laravel Integration: Wrap in a service class (e.g., app/Services/PkiService.php) to abstract key management and signing logic.

2. Certificate Validation

  • Pattern: Validate certificates against a trusted store (e.g., root CA).
    $validator = new CertificateValidator();
    $validator->addTrustedCertificate($rootCaCertificate);
    $isValid = $validator->validate($certificate, new \DateTimeImmutable());
    
  • Laravel Middleware: Create middleware to validate client certificates in mTLS scenarios:
    public function handle($request, Closure $next) {
        $clientCert = $request->getClientCert();
        if (!$this->pkiService->validateCertificate($clientCert)) {
            abort(403, 'Invalid client certificate');
        }
        return $next($request);
    }
    

3. Certificate Revocation (CRL/OCSP)

  • Pattern: Generate and validate Certificate Revocation Lists (CRL).
    $crl = new Crl(
        $issuer,
        new \DateTimeImmutable(),
        new \DateTimeImmutable('+1 month'),
        [$revokedCertificate1, $revokedCertificate2]
    );
    $crl->sign($caPrivateKey);
    $pem = $crl->toPem();
    
  • Laravel Cache: Store CRLs in Redis/Memcached for low-latency validation.

4. ASN.1/DER Parsing

  • Pattern: Parse custom ASN.1 structures (e.g., proprietary extensions).
    $derData = file_get_contents('certificate.der');
    $asn1 = new Asn1();
    $parsed = $asn1->decode($derData);
    

Integration Tips

  1. Key Management:

    • Use Laravel’s filesystem or cache to store private keys securely (e.g., encrypted in storage/app/pki/).
    • Example:
      $privateKey = openssl_pkey_get_private(
          file_get_contents(storage_path('app/pki/ca.key'))
      );
      
  2. Configuration:

    • Centralize PKI settings in config/pki.php:
      return [
          'ca' => [
              'path' => storage_path('app/pki/ca.crt'),
              'private_key' => storage_path('app/pki/ca.key'),
          ],
          'validation' => [
              'trusted_cas' => [storage_path('app/pki/trusted/root.crt')],
          ],
      ];
      
  3. Artisan Commands:

    • Create CLI tools for certificate management:
      // app/Console/Commands/IssueCertificate.php
      public function handle() {
          $cert = $this->pkiService->issueCertificate(
              $this->argument('subject'),
              $this->argument('days')
          );
          file_put_contents($this->argument('output'), $cert->toPem());
      }
      
    • Register in app/Console/Kernel.php:
      protected $commands = [
          Commands\IssueCertificate::class,
      ];
      
  4. Event Listeners:

    • Trigger events for certificate lifecycle (e.g., issuance, expiration).
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          \SpomkyLabs\PkiFramework\Events\CertificateIssued::class => [
              \App\Listeners\LogCertificateIssuance::class,
          ],
      ];
      
  5. Testing:

    • Use pki-framework's test utilities to mock certificates in PHPUnit:
      $certificate = CertificateFactory::createSelfSignedCertificate(
          'CN=test.example.com',
          new \DateTimeImmutable('-1 day'),
          new \DateTimeImmutable('+1 day')
      );
      

Gotchas and Tips

Pitfalls

  1. Key Management:

    • Gotcha: Hardcoding private keys in code or version control. Fix: Use Laravel’s encryption (config/app.php key) or environment variables:
      $privateKey = openssl_pkey_get_private(
          env('PKI_CA_PRIVATE_KEY')
      );
      
    • Tip: Rotate keys periodically using openssl genpkey and update the Laravel config.
  2. Time Validation:

    • Gotcha: Timezone mismatches causing false validation failures. Fix: Use DateTimeImmutable with explicit timezone:
      $now = new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
      $isValid = $certificate->isValid($now);
      
  3. CRL/OCSP Cache:

    • Gotcha: Stale CRLs leading to false positives for revoked certificates. Fix: Implement a cache invalidation strategy (e.g., refresh every 6 hours):
      $crl = Cache::remember('pki_crl', 6 * 3600, function () {
          return CrlFactory::fromPem(file_get_contents($crlPath));
      });
      
  4. ASN.1 Parsing:

    • Gotcha: Malformed DER data crashing the parser. Fix: Validate input with Asn1::isValid() or wrap in a try-catch:
      try {
          $asn1 = new Asn1();
          $parsed = $asn1->decode($derData);
      } catch (\SpomkyLabs\PkiFramework\Exception\Asn1Exception $e) {
          Log::error('Invalid ASN.1 data', ['error' => $e->getMessage()]);
          return false;
      }
      
  5. Signature Algorithms:

    • Gotcha: Unsupported algorithms (e.g., RSASSA-PSS) failing silently. Fix: Explicitly specify algorithms when signing:
      $certificate->sign($privateKey, 'sha256WithRSAEncryption');
      
  6. Performance:

    • Gotcha: Heavy validation logic in request pipelines. Fix: Cache validated certificates (e.g., in Redis) or use Laravel’s viaMiddleware for non-critical paths.

Debugging Tips

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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope