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

Phpasn1 Laravel Package

fgrosse/phpasn1

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require fgrosse/phpasn1
    

    Ensure your composer.json enforces PHP 7.4 or lower (due to lack of PHP 8.x support):

    "config": {
      "platform": {
        "php": "7.4"
      }
    }
    
  2. First Use Case: Encode a simple ASN.1 Sequence (e.g., for a CSR or certificate):

    use FG\ASN1\Universal\Sequence;
    use FG\ASN1\Universal\Integer;
    use FG\ASN1\Universal\IA5String;
    
    $sequence = new Sequence(
        new Integer(12345),
        new IA5String('example.com')
    );
    $binary = $sequence->getBinary();
    $base64 = base64_encode($binary);
    
  3. Decoding: Parse a base64-encoded ASN.1 payload:

    use FG\ASN1\ASNObject;
    
    $binary = base64_decode('MII...'); // Your DER-encoded data
    $asnObject = ASNObject::fromBinary($binary);
    
  4. Key Classes to Know:

    • FG\ASN1\Universal\* (e.g., Integer, Sequence, Set, ObjectIdentifier).
    • FG\ASN1\TemplateParser (for structured validation).
    • FG\ASN1\OID (predefined Object Identifiers like RSA_ENCRYPTION).

Implementation Patterns

Usage Patterns

1. Building ASN.1 Structures

  • Hierarchical Construction: Use Sequence/Set to nest ASN.1 types (e.g., for X.509 certificates):
    $subject = new Sequence(
        new Set(
            new ObjectIdentifier('2.5.4.3'), // CN
            new PrintableString('example.com')
        ),
        // ... other fields
    );
    
  • Reusable Components: Encapsulate common structures in Laravel services:
    // app/Services/Asn1/CertificateBuilder.php
    class CertificateBuilder {
        public function buildSubject(): Sequence {
            return new Sequence(
                new Set(
                    new ObjectIdentifier('2.5.4.3'),
                    new PrintableString('example.com')
                )
            );
        }
    }
    

2. Decoding with Templates

  • Validate Structure: Use TemplateParser to enforce schema compliance:
    $template = [
        Identifier::SEQUENCE => [
            Identifier::INTEGER,
            Identifier::SEQUENCE => [
                Identifier::OBJECT_IDENTIFIER,
                Identifier::NULL_OBJECT,
            ]
        ]
    ];
    $parser = new TemplateParser();
    $object = $parser->parseBinary($binary, $template);
    
  • Error Handling: Wrap parsing in a try-catch to handle malformed data:
    try {
        $object = $parser->parseBinary($binary, $template);
    } catch (\Exception $e) {
        Log::error("Invalid ASN.1 payload: " . $e->getMessage());
        throw new \InvalidArgumentException("Malformed ASN.1 data");
    }
    

3. Integration with Laravel

  • Service Container Binding: Bind the parser to Laravel’s IoC container:
    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind(TemplateParser::class, function () {
            return new TemplateParser();
        });
    }
    
  • Request/Response Handling: Decode ASN.1 payloads in middleware or controllers:
    // app/Http/Middleware/DecodeAsn1Payload.php
    public function handle($request, Closure $next) {
        if ($request->hasHeader('content-type') && str_contains($request->header('content-type'), 'application/asn.1')) {
            $binary = $request->getContent();
            $request->merge(['asn1' => ASNObject::fromBinary($binary)]);
        }
        return $next($request);
    }
    

4. Cryptographic Workflows

  • CSR Generation: Combine with OpenSSL for key generation:
    $privateKey = openssl_pkey_new(['digest_alg' => 'sha256']);
    openssl_pkey_export($privateKey, $pem);
    $publicKey = openssl_pkey_get_details($privateKey)['key'];
    $csr = (new \FG\ASN1\CSR())
        ->setSubject($subject)
        ->setPublicKey($publicKey);
    $der = $csr->encode();
    

5. Storage and Retrieval

  • Database Storage: Serialize ASN.1 objects to JSON for storage:
    $asn1Data = $object->toArray(); // Implement toArray() in your model
    $model->asn1_data = json_encode($asn1Data);
    $model->save();
    
  • Rehydration: Reconstruct objects from storage:
    $storedData = json_decode($model->asn1_data, true);
    $object = ASNObject::fromArray($storedData); // Hypothetical method
    

Workflows

1. Certificate Authority (CA) Tool

  • Steps:
    1. Decode a CSR (using TemplateParser).
    2. Validate fields (e.g., subject, public key).
    3. Sign with CA private key (using OpenSSL).
    4. Encode the certificate (using FG\ASN1\Certificate).
  • Example:
    $csrBinary = base64_decode($request->input('csr'));
    $csr = $parser->parseBinary($csrBinary, $csrTemplate);
    $cert = $ca->sign($csr, $caPrivateKey);
    return response()->json(['certificate' => base64_encode($cert->encode())]);
    

2. Legacy System Integration

  • Steps:
    1. Capture binary ASN.1 payloads from a legacy system (e.g., SNMP trap).
    2. Decode using ASNObject::fromBinary().
    3. Transform into a Laravel model or API response.
  • Example:
    $payload = $legacySystem->fetchPayload();
    $asn1 = ASNObject::fromBinary($payload);
    $event = new LegacyEvent($asn1->toArray());
    event(new LegacyPayloadReceived($event));
    

3. Dynamic Schema Handling

  • Steps:
    1. Define a dynamic template based on runtime conditions.
    2. Parse incoming ASN.1 data against the template.
  • Example:
    $template = buildTemplateFromConfig($config);
    $object = $parser->parseBinary($binary, $template);
    

Integration Tips

1. Pair with OpenSSL

  • Use OpenSSL for cryptographic operations (e.g., signing) and PHPASN1 for ASN.1 structure manipulation.
  • Example: Generate a CSR with PHPASN1, then sign it with OpenSSL.

2. Leverage Laravel Events

  • Trigger events for ASN.1 operations (e.g., CertificateGenerated, CsrReceived):
    event(new CertificateGenerated($certificate));
    

3. Queue Long-Running Tasks

  • Offload ASN.1 parsing/encoding to queues (e.g., for large CRLs):
    ProcessAsn1Job::dispatch($binaryData, $template)->onQueue('asn1');
    

4. Testing

  • Unit Tests: Test encoding/decoding round-trips:
    public function testEncodingDecodingRoundTrip() {
        $original = new Sequence(new Integer(123));
        $binary = $original->getBinary();
        $decoded = ASNObject::fromBinary($binary);
        $this->assertEquals($original->toArray(), $decoded->toArray());
    }
    
  • Integration Tests: Mock legacy systems or external APIs that return ASN.1 data.

5. Performance

  • For large payloads (e.g., CRLs), consider:
    • Streaming parsing (if the package supports it; likely not).
    • Caching decoded objects (e.g., Redis) if reused frequently.

Gotchas and Tips

Pitfalls

1. PHP Version Incompatibility

  • Issue: The package is not tested on PHP 8.x. Attributes like #[\ReturnTypeWillChange] may cause deprecation warnings or errors.
  • Workaround:
    • Pin to PHP 7.4 in composer.json:
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