freedsx/asn1

PHP 的 ASN.1 库。

0.4.7 2023-06-06 16:47 UTC

This package is auto-updated.

Last update: 2024-09-06 19:28:32 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;
    }
}