1# FreeDSx ASN1 ![](https://github.com/FreeDSx/ASN1/workflows/Analysis/badge.svg) ![](https://github.com/FreeDSx/ASN1/workflows/Build/badge.svg) [![codecov](https://codecov.io/gh/FreeDSx/ASN1/branch/master/graph/badge.svg)](https://codecov.io/gh/FreeDSx/ASN1) 2FreeDSx ASN1 is a PHP library for dealing with ASN.1 data structures. Its original focus was on ASN.1 BER encoding used in 3LDAP as part of the FreeDSx LDAP library. It was moved to its own library to allow for additional encoders and reuse in 4other projects. 5 6# Getting Started 7 8Install via composer: 9 10```bash 11composer require freedsx/asn1 12``` 13 14## Encoding 15 16To encode an ASN.1 structure you can use the helper methods of the Asn1 class and an encoder: 17 18```php 19use FreeDSx\Asn1\Asn1; 20use FreeDSx\Asn1\Encoders; 21 22# Create the ASN.1 structure you need... 23$asn1 = Asn1::sequence( 24 Asn1::integer(9999), 25 Asn1::octetString('foo'), 26 Asn1::boolean(true) 27); 28 29# Encoded $bytes will now contain the BER binary representation of a sequence containing: 30# - An integer type of value 9999 31# - An octet string type of value 'foo' 32# - A boolean type of true 33$bytes = Encoders::ber()->encode($asn1); 34 35# Encode using the more strict DER encoder 36$bytes = Encoders::der()->encode($asn1); 37``` 38 39## Decoding 40 41To decode an ASN.1 structure you can get an encoder and call decode then parse it out: 42 43```php 44use FreeDSx\Asn1\Asn1; 45use FreeDSx\Asn1\Encoders; 46use FreeDSx\Asn1\Type\SequenceType; 47use FreeDSx\Asn1\Type\OctetStringType; 48use FreeDSx\Asn1\Type\IntegerType; 49use FreeDSx\Asn1\Type\BooleanType; 50 51# Assuming bytes contains the binary BER encoded sequence described in the encoding section 52# Get a BER encoder instance, call decode on it, and $pdu will now be a sequence object. 53$pdu = Encoders::ber()->decode($bytes); 54 55# You could also decode using DER, if that's what you're expecting... 56$pdu = Encoders::der()->decode($bytes); 57 58# Validate the structure you are expecting... 59if (!($pdu instanceof SequenceType && count($pdu) === 3)) { 60 echo "Decoded structure is invalid.".PHP_EOL; 61 exit; 62} 63 64# Loop through the sequence and check the individual types it contains... 65foreach ($pdu as $i => $type) { 66 if ($i === 0 && $type instanceof IntegerType) { 67 var_dump($type->getValue()); 68 } elseif ($i === 1 && $type instanceof OctetStringType) { 69 var_dump($type->getValue()); 70 } elseif ($i === 2 && $type instanceof BooleanType) { 71 var_dump($type->getValue()); 72 } else { 73 echo "Invalid type encountered.".PHP_EOL; 74 exit; 75 } 76} 77``` 78