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

Asn1 Laravel Package

vakata/asn1

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require vakata/asn1
    

    No additional configuration is required for basic usage.

  2. First Use Case: Parsing ASN.1 Data Import the Vakata\ASN1 namespace and parse a DER-encoded string:

    use Vakata\ASN1\ASN1;
    
    $derData = file_get_contents('path/to/der.der');
    $asn1 = ASN1::decode($derData);
    print_r($asn1);
    

    Output will be a structured array representing the ASN.1 data.

  3. First Use Case: Building ASN.1 Data Construct a simple ASN.1 structure and encode it:

    use Vakata\ASN1\ASN1;
    
    $data = [
        'integer' => 123,
        'string' => 'Hello, ASN1!',
        'sequence' => [
            'octet-string' => hex2bin('12345678'),
        ],
    ];
    $encoded = ASN1::encode($data);
    file_put_contents('output.der', $encoded);
    
  4. Key Classes to Know

    • ASN1: Main class for encoding/decoding.
    • ASN1Element: Represents individual ASN.1 elements (e.g., integers, sequences).
    • ASN1Exception: Handle parsing/encoding errors.

Implementation Patterns

Common Workflows

1. Parsing Certificates or PKCS#10 Requests

ASN.1 is widely used in X.509 certificates and CSRs. Parse a certificate:

$certData = file_get_contents('cert.der');
$cert = ASN1::decode($certData);

// Extract subject (assuming it's a sequence)
$subject = $cert['tbsCertificate']['subject'];

2. Building PKCS#12 (PFX) Structures

Construct a PKCS#12 AuthSafe structure:

$p12Data = [
    'authSafe' => [
        'version' => 0,
        'friendlyName' => 'My Certificate',
        'localKeyId' => hex2bin('1234567890abcdef'),
        'data' => [
            'certificate' => $certificateData,
            'privateKey' => $privateKeyData,
        ],
    ],
];
$encodedP12 = ASN1::encode($p12Data);

3. Handling OIDs (Object Identifiers)

Use OIDs to tag structures (e.g., for extensions):

$extension = [
    'id' => '1.2.3.4.5', // Example OID
    'critical' => false,
    'value' => $criticalExtensionData,
];

4. Recursive Data Handling

ASN.1 often nests structures. Traverse recursively:

function traverseASN1($data, $path = '') {
    foreach ($data as $key => $value) {
        $currentPath = $path ? "$path.$key" : $key;
        if (is_array($value)) {
            traverseASN1($value, $currentPath);
        } else {
            echo "Path: $currentPath, Value: " . print_r($value, true);
        }
    }
}
traverseASN1($asn1Data);

Integration Tips

1. Laravel Service Providers

Register the package as a singleton for global access:

// app/Providers/AppServiceProvider.php
public function register() {
    $this->app->singleton('asn1', function () {
        return new \Vakata\ASN1\ASN1();
    });
}

Use it in controllers:

$asn1 = app('asn1');
$data = $asn1->decode($request->file('cert')->getContent());

2. Artisan Commands

Create a command to validate ASN.1 files:

// app/Console/Commands/ValidateAsn1.php
public function handle() {
    $file = $this->argument('file');
    $asn1 = ASN1::decode(file_get_contents($file));
    $this->info('ASN.1 file is valid!');
}

Register it in app/Console/Kernel.php:

protected $commands = [
    \App\Console\Commands\ValidateAsn1::class,
];

3. Form Request Validation

Validate ASN.1 data in Laravel requests:

public function rules() {
    return [
        'certificate' => 'required|file|mimes:der',
    ];
}

public function withValidator($validator) {
    $validator->after(function ($validator) {
        if ($validator->errors()->any()) return;
        $certData = file_get_contents($this->certificate->getRealPath());
        try {
            ASN1::decode($certData);
        } catch (ASN1Exception $e) {
            $validator->errors()->add('certificate', 'Invalid ASN.1 format.');
        }
    });
}

4. API Responses

Return ASN.1-encoded data in API responses:

return response()->json([
    'asn1_data' => base64_encode(ASN1::encode($data)),
]);

Gotchas and Tips

Pitfalls

1. DER vs. PER/BER

  • The package primarily supports DER (Distinguished Encoding Rules).
  • If working with BER (Basic Encoding Rules) or PER (Packed Encoding Rules), decoding may fail. Use a tool like openssl asn1parse to verify encoding rules.

2. Tagging Ambiguities

  • ASN.1 allows implicit/explicit tags. The parser may not infer tags correctly without explicit hints.
  • Fix: Manually specify tags in your data structure:
    $data = [
        'tag:0' => [ // Explicit tag 0
            'value' => 'data',
        ],
    ];
    

3. Recursive Structures

  • Deeply nested structures can cause stack overflows or memory issues.
  • Fix: Limit recursion depth or process data in chunks.

4. Endianness for Integers

  • Integers are encoded in big-endian by default. Ensure your data matches this.
  • Fix: Use hex2bin for manual hex strings to avoid encoding issues.

5. Unknown Tags

  • The parser may skip unknown tags silently. Enable strict mode to throw exceptions:
    $asn1 = ASN1::decode($data, ASN1::STRICT);
    

Debugging Tips

1. Pretty-Print ASN.1 Data

Use print_r with ASN1Element objects:

function prettyPrintASN1($data, $indent = 0) {
    foreach ($data as $key => $value) {
        echo str_repeat('  ', $indent) . "$key: ";
        if (is_array($value)) {
            echo "\n";
            prettyPrintASN1($value, $indent + 1);
        } else {
            echo print_r($value, true) . "\n";
        }
    }
}
prettyPrintASN1($asn1Data);

2. Validate with OpenSSL

Cross-validate parsed data using OpenSSL CLI:

openssl asn1parse -in input.der -inform DER

3. Handle Encoding Errors

Wrap decoding in a try-catch:

try {
    $data = ASN1::decode($derData);
} catch (ASN1Exception $e) {
    Log::error('ASN.1 decode error: ' . $e->getMessage());
    throw new \Exception('Invalid ASN.1 data');
}

Extension Points

1. Custom Tag Handlers

Extend the parser to handle proprietary tags:

ASN1::setTagHandler(1234, function ($value) {
    return ['custom' => $value];
});

2. Hooks for Encoding/Decoding

Override default behavior:

ASN1::setEncoderHook('integer', function ($value) {
    return hex2bin(dechex($value)); // Custom encoding
});

3. Integrate with Laravel Filesystem

Store ASN.1 files in Laravel storage:

use Illuminate\Support\Facades\Storage;

$path = Storage::disk('s3')->put('certs/cert.der', $encodedData);

**4. Use with

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.
terminal42/code-quality-tools
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