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 PKI: X.509 certificates, ASN.1 (X.690 DER) encoding/decoding, X.501/X.520 DN parsing, PEM (RFC 7468) support, and cryptographic/PKCS-related ASN.1 types. mbstring required; gmp/bcmath recommended.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spomky-labs/pki-framework
    

    Ensure your composer.json meets the requirements (PHP ≥8.1, mbstring, and optionally gmp/bcmath).

  2. First Use Case: Parse an existing X.509 certificate from a PEM file:

    use SpomkyLabs\PkiFramework\Certificate;
    
    $certificate = Certificate::fromFile('path/to/certificate.pem');
    $subject = $certificate->getSubject();
    $notBefore = $certificate->getValidity()->getNotBefore();
    
  3. Key Classes to Explore:

    • Certificate: Core class for X.509 certificates.
    • CertificateFactory: Generate new certificates.
    • CertificateRevocationList: Handle CRLs.
    • Asn1: Work with ASN.1 structures directly.
    • Pem: Encode/decode PEM formats.
  4. Where to Look First:


Implementation Patterns

Core Workflows

1. Certificate Parsing and Validation

  • Parse a certificate:
    $cert = Certificate::fromFile('cert.pem');
    // or from DER
    $cert = Certificate::fromDER(file_get_contents('cert.der'));
    
  • Validate a certificate against a CA:
    $caCert = Certificate::fromFile('ca.pem');
    $cert->validate($caCert);
    
  • Check expiration:
    if ($cert->isValid()) {
        // Certificate is valid
    }
    

2. Certificate Generation

  • Generate a self-signed certificate:
    use SpomkyLabs\PkiFramework\CertificateFactory;
    
    $factory = new CertificateFactory();
    $cert = $factory->createSelfSigned(
        'CN=My CA',
        'CN=My Server',
        'sha256WithRSAEncryption',
        365
    );
    
  • Generate a certificate signed by a CA:
    $caCert = Certificate::fromFile('ca.pem');
    $caKey = PrivateKey::fromFile('ca.key');
    $cert = $factory->createSigned(
        $caCert,
        $caKey,
        'CN=My Server',
        'sha256WithRSAEncryption',
        365
    );
    

3. PEM and DER Encoding/Decoding

  • Convert to PEM:
    $pem = $cert->toPem();
    
  • Convert to DER:
    $der = $cert->toDER();
    
  • Parse PEM:
    $cert = Certificate::fromPem($pemString);
    

4. Certificate Revocation (CRL)

  • Create a CRL:
    use SpomkyLabs\PkiFramework\CertificateRevocationList;
    
    $crl = new CertificateRevocationList();
    $crl->addRevokedCertificate($revokedCert, new \DateTime('now'));
    $crl->sign($caCert, $caKey);
    
  • Validate against a CRL:
    $crl = CertificateRevocationList::fromFile('crl.pem');
    $cert->validate($crl);
    

5. ASN.1 Manipulation

  • Parse ASN.1 data:
    use SpomkyLabs\PkiFramework\Asn1;
    
    $asn1 = Asn1::fromDER($derData);
    
  • Encode to DER:
    $der = $asn1->toDER();
    

6. Integration with Laravel

  • Store certificates in the database:
    $certData = $cert->toDER();
    $model->certificate_data = $certData;
    $model->save();
    
  • Validate certificates in middleware:
    public function handle(Request $request, Closure $next) {
        $clientCert = $request->getCertificate(); // Assuming you extract the cert
        $caCert = Certificate::fromFile(storage_path('ca.pem'));
        $clientCert->validate($caCert);
        return $next($request);
    }
    
  • Use in Laravel Passport/Sanctum:
    // Customize token validation to check certificate SANs
    Passport::tokensCan([
        'certificate-bound-token' => function ($user, $token) {
            $cert = $token->getCertificate(); // Hypothetical; adapt to your needs
            return $cert->getSubjectAlternativeNames()->contains('email:user@example.com');
        }
    ]);
    

7. Custom Extensions and OIDs

  • Add custom extensions:
    $extension = new Extension(
        new ObjectIdentifier('1.2.3.4'), // Your custom OID
        false, // Critical
        $asn1Data // Your ASN.1 data
    );
    $cert->addExtension($extension);
    
  • Parse custom extensions:
    $extensions = $cert->getExtensions();
    foreach ($extensions as $extension) {
        if ($extension->getOid()->equals('1.2.3.4')) {
            // Handle custom extension
        }
    }
    

Integration Tips

1. Key Management

  • Use Laravel’s filesystem or encryption services to securely store private keys:
    use Illuminate\Support\Facades\Storage;
    
    Storage::put('private/ca.key', $caKey->toPem());
    
  • Consider using Laravel Forge or Vault for key rotation.

2. Caching

  • Cache parsed certificates to avoid reprocessing:
    $cacheKey = 'cert_' . md5($certPath);
    $cert = Cache::remember($cacheKey, now()->addHours(1), function () use ($certPath) {
        return Certificate::fromFile($certPath);
    });
    

3. Error Handling

  • Wrap PKI operations in try-catch blocks:
    try {
        $cert->validate($caCert);
    } catch (CertificateException $e) {
        Log::error('Certificate validation failed: ' . $e->getMessage());
        abort(403, 'Invalid certificate');
    }
    

4. Testing

  • Use the library’s test suite as a reference for writing unit tests:
    public function testCertificateValidation() {
        $caCert = Certificate::fromFile('tests/fixtures/ca.pem');
        $validCert = Certificate::fromFile('tests/fixtures/valid.pem');
        $invalidCert = Certificate::fromFile('tests/fixtures/invalid.pem');
    
        $this->assertTrue($validCert->validate($caCert));
        $this->assertFalse($invalidCert->validate($caCert));
    }
    

5. Logging

  • Log critical PKI events (e.g., certificate issuance, revocation):
    Log::info('Issued certificate', [
        'subject' => $cert->getSubject()->getName(),
        'serial' => $cert->getSerialNumber(),
    ]);
    

6. Performance

  • For high-throughput validation, consider preloading CA certificates:
    $caCerts = collect([
        Certificate::fromFile('ca1.pem'),
        Certificate::fromFile('ca2.pem'),
    ]);
    
  • Use gmp or bcmath for large-key operations to improve performance.

Gotchas and Tips

Pitfalls

1. Key Management

  • Pitfall: Accidentally committing private keys to version control.
    • Fix: Use .gitignore and Laravel’s environment-based storage (e.g., storage/app/private).
    • Tip: Use Laravel’s config/filesystems.php to restrict access to sensitive files.

2. Certificate Validation Logic

  • Pitfall: Overly permissive validation (e.g., ignoring expiration or revocation checks).
    • Fix: Always validate against a trusted CA and check:
      $cert->validate($caCert);
      $cert->isValid(); // Checks expiration
      
  • Tip: Implement a custom validator:
    $validator = new CertificateValidator();
    $validator->setCaCert($caCert);
    $validator->setCheckRevocation
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport