cymapgt/asn1

PHP的ASN.1库。

0.2.1 2018-06-03 22:58 UTC

This package is auto-updated.

Last update: 2024-09-15 12:17:02 UTC


README

FreeDSx ASN1是一个用于处理ASN.1数据结构的PHP库。它的原始重点是ASN.1 BER编码,该编码用于LDAP作为FreeDSx LDAP库的一部分。它被移动到自己的库中,以便允许使用额外的编码器并在其他项目中重用。

入门指南

通过composer安装

composer require freedsx/asn1

编码

要编码ASN.1结构,您可以使用Asn1类和编码器的辅助方法。

use FreeDSx\Asn1\Asn1;
use FreeDSx\Asn1\Encoders;

# Create the ASN.1 structure you need...
$asn1 = Asn1::sequence(
    Asn1::integer(9999),
    Asn1::octetString('foo'),
    Asn1::boolean(true)
);

# Encoded $bytes will now contain the BER binary representation of a sequence containing:
#  - An integer type of value 9999
#  - An octet string type of value 'foo'
#  - A boolean type of true
$bytes = Encoders::ber()->encode($asn1);

# Encode using the more strict DER encoder
$bytes = Encoders::der()->encode($asn1);

解码

要解码ASN.1结构,您可以获取一个编码器,调用decode然后解析它。

use FreeDSx\Asn1\Asn1;
use FreeDSx\Asn1\Encoders;
use FreeDSx\Asn1\Type\SequenceType;
use FreeDSx\Asn1\Type\OctetStringType;
use FreeDSx\Asn1\Type\IntegerType;
use FreeDSx\Asn1\Type\BooleanType;

# Assuming bytes contains the binary BER encoded sequence described in the encoding section
# Get a BER encoder instance, call decode on it, and $pdu will now be a sequence object.
$pdu = Encoders::ber()->decode($bytes);

# You could also decode using DER, if that's what you're expecting...
$pdu = Encoders::der()->decode($bytes);

# Validate the structure you are expecting...
if (!($pdu instanceof SequenceType && count($pdu) === 3)) {
    echo "Decoded structure is invalid.".PHP_EOL;
    exit;
}

# Loop through the sequence and check the individual types it contains...
foreach ($pdu as $i => $type) {
    if ($i === 0 && $type instanceof IntegerType) {
        var_dump($type->getValue());
    } elseif ($i === 1 && $type instanceof OctetStringType) {
        var_dump($type->getValue());
    } elseif ($i === 2 && $type instanceof BooleanType) {
        var_dump($type->getValue());
    } else {
        echo "Invalid type encountered.".PHP_EOL;
        exit;
    }
}