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

Xmlsecurity Laravel Package

ass/xmlsecurity

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer in your Laravel project:

    composer require ass/xmlsecurity:dev-master
    

    (Note: Use dev-master due to the last release being from 2015; pin the version in composer.json for stability.)

  2. First Use Case: Signing XML

    use ass\XmlSecurity\XmlSecurity;
    use ass\XmlSecurity\XmlSecurityKey;
    
    $xml = new \SimpleXMLElement('<root><message>Hello</message></root>');
    $key = new XmlSecurityKey(XmlSecurityKey::RSA_SHA256, array('type' => 'private'));
    $key->loadKey('path/to/private_key.pem', null, array('password' => 'your_password'));
    
    $obj = new XmlSecurity($key);
    $obj->idAttributes = array(array('Id', 'URI')); // Optional: Configure ID attributes
    $obj->canonicalize($xml);
    $obj->sign($xml, '', XmlSecurity::ELEMENT | XmlSecurity::EXCL_C14N);
    echo $xml->asXML();
    
  3. First Use Case: Encrypting XML

    $key = new XmlSecurityKey(XmlSecurityKey::RSA_OAEP, array('type' => 'public'));
    $key->loadKey('path/to/public_key.pem');
    
    $obj = new XmlSecurity($key);
    $obj->encrypt($xml, '', XmlSecurity::ELEMENT);
    echo $obj->xml();
    
  4. Key Management Store keys securely (e.g., Laravel's config/filesystems.php or environment variables) and avoid hardcoding paths.


Implementation Patterns

Common Workflows

1. Signing XML Documents

  • Workflow:

    1. Load XML content (string or SimpleXMLElement).
    2. Initialize XmlSecurity with a private key.
    3. Canonicalize the XML (e.g., canonicalize($xml)).
    4. Sign the XML (sign($xml, $id, $flags)).
    5. Output the signed XML.
  • Example: Signing a SOAP Response

    $soapXml = new \SimpleXMLElement($soapResponse);
    $obj->sign($soapXml->Body, 'BodyID', XmlSecurity::EXCL_C14N);
    return $obj->xml();
    

2. Encrypting Sensitive Data

  • Workflow:

    1. Load XML content.
    2. Initialize XmlSecurity with a public key.
    3. Encrypt specific elements (encrypt($xml, $id, $flags)).
    4. Output the encrypted XML.
  • Example: Encrypting a Payment Element

    $paymentXml = new \SimpleXMLElement('<payment><amount>100</amount></payment>');
    $obj->encrypt($paymentXml->amount, 'AmountID', XmlSecurity::ELEMENT);
    return $obj->xml();
    

3. Verifying Signatures

  • Workflow:

    1. Load signed XML.
    2. Initialize XmlSecurity with a public key.
    3. Verify the signature (verify($xml)).
    4. Handle validation (e.g., throw exceptions or return boolean).
  • Example: Validating a Signed Request

    $obj->key = new XmlSecurityKey(XmlSecurityKey::RSA_SHA256, array('type' => 'public'));
    $obj->key->loadKey('path/to/public_key.pem');
    $isValid = $obj->verify($signedXml);
    if (!$isValid) {
        throw new \Exception("Invalid signature");
    }
    

4. Decrypting XML

  • Workflow:

    1. Load encrypted XML.
    2. Initialize XmlSecurity with a private key.
    3. Decrypt elements (decrypt($xml)).
    4. Output decrypted XML.
  • Example: Decrypting a Confidential Field

    $obj->key = new XmlSecurityKey(XmlSecurityKey::RSA_OAEP, array('type' => 'private'));
    $obj->key->loadKey('path/to/private_key.pem');
    $obj->decrypt($encryptedXml);
    return $obj->xml();
    

Integration Tips

Laravel-Specific Patterns

  1. Service Provider Binding Bind the library to Laravel's container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton('xmlsecurity', function () {
            return new XmlSecurity($this->app->make('xmlsecurity.key'));
        });
    }
    
  2. Key Management with Laravel Use Laravel's filesystem or cache to store/retrieve keys:

    // config/xmlsecurity.php
    'keys' => [
        'private' => storage_path('app/keys/private.pem'),
        'public'  => storage_path('app/keys/public.pem'),
    ];
    
  3. Middleware for Signed Requests Validate XML signatures in middleware:

    // app/Http/Middleware/ValidateXmlSignature.php
    public function handle($request, Closure $next)
    {
        $xml = new \SimpleXMLElement($request->xml);
        $obj = app('xmlsecurity');
        if (!$obj->verify($xml)) {
            abort(403, 'Invalid signature');
        }
        return $next($request);
    }
    
  4. Queue Jobs for Async Processing Offload XML signing/encryption to queues:

    // app/Jobs/SignXmlJob.php
    public function handle()
    {
        $obj = new XmlSecurity($this->key);
        $obj->sign($this->xml, $this->id);
        $this->xml->save($this->path);
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated/Unmaintained Package

    • The last release is from 2015; expect compatibility issues with PHP 8.x or modern Laravel versions.
    • Mitigation: Use dev-master and pin the version in composer.json. Test thoroughly.
  2. Key Loading Failures

    • Incorrect key formats (e.g., wrong PEM headers) or passwords cause silent failures.
    • Debugging: Check XmlSecurityKey::loadKey() return value (returns false on failure).
    • Tip: Validate keys with OpenSSL:
      openssl rsa -in private_key.pem -check
      
  3. XML Canonicalization Issues

    • Mismatched canonicalization methods (e.g., EXCL_C14N vs. INCL_C14N) between signing/verification.
    • Tip: Always use the same flags for signing and verification.
  4. Namespace Conflicts

    • The library uses ass\XmlSecurity namespace, but some methods (e.g., canonicalize) may conflict with Laravel helpers.
    • Mitigation: Use fully qualified names:
      $obj->canonicalize($xml, XmlSecurity::EXCL_C14N);
      
  5. Memory Limits for Large XML

    • Processing large XML files may hit PHP's memory limit.
    • Tip: Use libxml_disable_entity_loader(false) cautiously or stream XML with SimpleXML's LIBXML_NOENT flag.
  6. Timezone Mismatches in Signatures

    • Timestamps in signatures may fail if the system timezone differs from the signing environment.
    • Tip: Set a consistent timezone before signing:
      date_default_timezone_set('UTC');
      

Debugging Tips

  1. Enable LibXML Errors

    libxml_use_internal_errors(true);
    $obj->sign($xml);
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        error_log($error->message);
    }
    libxml_clear_errors();
    
  2. Log Raw XML Compare signed/unsigned XML to identify issues:

    file_put_contents('debug_unsigned.xml', $unsignedXml->asXML());
    file_put_contents('debug_signed.xml', $signedXml->asXML());
    
  3. Validate with Online Tools Use tools like XML Signature Validator to verify signatures independently.


Extension Points

  1. Custom Canonicalization Override canonicalize() for custom XML transformations:

    $obj->canonicalize = function ($xml) {
        // Custom logic (e.g., remove comments)
        return $xml->asXML();
    };
    
  2. Key Rotation Hooks Extend XmlSecurityKey to add pre/post-load validation:

    class CustomXmlSecurityKey extends XmlSecurityKey {
        public function loadKey($res, $passphrase = null, $options = array()) {
            $result = parent::loadKey($res, $passphrase, $options);
            if (!$result) {
                event(new KeyLoadFailed($
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony