sop / asn1 Goto Github PK
View Code? Open in Web Editor NEWA PHP library for ASN.1 DER encoding and decoding.
Home Page: https://sop.github.io/asn1/
License: MIT License
A PHP library for ASN.1 DER encoding and decoding.
Home Page: https://sop.github.io/asn1/
License: MIT License
Hello,
How to create a Sequence of UTF8String?
$request = new Sequence(
new UTF8String($str)
);
creates a simple Sequence.
Thanks!
I am currently checking whether a string is a public key by doing this:
$key = base64_decode("MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAyl6XUhrx0v4zKaVpQ53GLYrKy6BR6s5gtSLorJ9FbwSVP+wIsMut2q3LaYpWeJuC1BIZ3isNsRqmkdlP4qaLYeCQOMr5VMJkzsjL/lkxt4jvxSCB8U0ms+dxgjFOWAzE1IA/HYwyVs1ge4FeXGcJ3lcYyZ2IFOJ+jXNee2tgzR8rdNWsV7Px9QutKm9YYkJ+xuBQ++Q4HdKTRgU7Xoq8n1lfgzAXSsHFIxdWbUJqK7WPUcY3kfX364N+0fKmmZysNlj6ZegK/295h+EQwJTTjVipIhWFR7xQ37mDv8sp/rxEyO51cLt0AUwdyReqOhkfzJMFCBufTQqnwBDP6CJ5JHfeXeIW/T3lYsmnYJiKwhJqe58mA5GG0zG5+fUfqPeSX7BzJN4kqF69/gQJlmJIGjxRy+9mW7rQJ7YD8pgqW3k+KUppcACiTuIldKgaUEvMhNNIj2GyAYk+ggTh6ULRaKAAPdTBonLWnEIUSzL3f6DuFgiaCeySKkeS7ARP2HQdKsIphUav8bScYxsfLw6+EAeSGklPWHbsJ4sdJWVrRzLWNIa04Xm0IzT8xZRVfoJoi09+yYY2GD62F1YWki7wTOhHSdOuZ9hSDRHkAHEjkReJp0o9SmbSROo9wYJ8wwOP2Fwx900XATvx702k2/YizvdR7Ytz9sA2zpVFXVgeLvMCAwEAAQ==");
$seq = Sequence::fromDER($key);
$oid = $seq->at(0)->at(0)->asObjectIdentifier()->oid();
and if $oid
equals 1.2.840.113549.1.1.1
then it is an RSA public key.
I am a bit sceptical about the ->at(0)->at(0)->
and can this change? How would you recommend getting the oid
?
Hi!
Just tried this lib to parse SNMP packets.
No luck. Seems like decoding data with identifiers of 'application' class does not supported.
Have you any plans to implement it?
Any workarounds? Some kind of extension points or hacks that I can use?
Thank you!
Hi! I'm doing the following:
// $file => "./01.crt" => https://www.acraiz.gob.ar/Content/Archivos/certificados/licenciados_acraiz2016/01.crt
$pem = Sop\CryptoEncoding\PEM::fromFile($file);
$cert = Sop\X509\Certificate\Certificate::fromPEM($pem);
And for that particular PEM file I'm getting:
PHP Fatal error: Uncaught InvalidArgumentException: Not a valid IA5String string. in /.../vendor/sop/asn1/lib/ASN1/Type/BaseString.php:31
Stack trace:
#0 /.../vendor/sop/asn1/lib/ASN1/Type/Primitive/IA5String.php(25): Sop\ASN1\Type\BaseString->__construct()
#1 /.../vendor/sop/asn1/lib/ASN1/Type/PrimitiveString.php(48): Sop\ASN1\Type\Primitive\IA5String->__construct()
#2 /.../vendor/sop/asn1/lib/ASN1/Element.php(211): Sop\ASN1\Type\PrimitiveString::_decodeFromDER()
#3 /.../vendor/sop/asn1/lib/ASN1/Type/Structure.php(372): Sop\ASN1\Element::fromDER()
#4 /.../vendor/sop/asn1/lib/ASN1/Type/Structure.php(348): Sop\ASN1\Type\Structure::_decodeDefiniteLength()
#5 /.../vendor/sop/asn1/lib/ASN1/Element.php(211): Sop\ASN1\Type\Structure::_decodeFromDER()
#6 /var/www/l in /.../vendor/sop/asn1/lib/ASN1/Type/PrimitiveString.php on line 50
It works if I override this validation in vendor/sop/asn1/lib/ASN1/Type/Primitive/IA5String.php
:
28 /**
29 * {@inheritdoc}
30 */
31 protected function _validateString(string $string): bool
32 {
33 return true;
34 //return 0 == preg_match('/[^\x01-\x7f]/', $string);
35 }
36 }
Am I doing something wrong, or is there some workaround to get over this?
Please help, I'm kind of desperate since I spent an entire day and I can't solve it. Thank you in advance!
Hi,
First, I'd like to thank you for this amazing library, it saved me a lot of time.
I'am trying to decode ASN1/DER data coming from Itunes In-App purchase receipt. Here is the schema I've found in their documentation:
ReceiptModule DEFINITIONS ::=
--
BEGIN
ReceiptAttribute ::= SEQUENCE {
type INTEGER,
version INTEGER,
value OCTET STRING
}
Payload ::= SET OF ReceiptAttribute
END
As far as I understand this, all value fields are supposed to contain OCTET STRING
. But, in the receipt fields documentation, there is different types such as UTF8STRING
, IA5STRING
, INTEGER
... I think they use OCTET STRING
actually containing other data types.
But, if I try to get an integer on an octet string field, I get the following error:
Uncaught UnexpectedValueException: INTEGER expected, got primitive OCTET STRING.
And, if I read the value as an OCTET STRING
, I get a weird string made of 3 non printable chars...
Any idea?
I have to say I'm very new to this kind of file and I might miss something very obvious.
Using int|string is done in a few places, but we can't set a return type of int
because large (and valid) tags, etc may be above the machines PHP_INT_MAX. We could use a \GMP instance for these cases.
Not sure what you think about this one, API consumers would have to do it wherever they want to use a tag as a key - which we would have do in some places too (tag to tag name I think, plus some constants will just be integers..)
Let me know if it's too invasive to be worth the parameter / return type hints, otherwise I'll try write this up soon
FILE: asn1/lib/ASN1/Type/Primitive/Real.php
---------------------------------------------------------------------------------------------------------------------------------------------------------------
FOUND 2 ERRORS AFFECTING 2 LINES
---------------------------------------------------------------------------------------------------------------------------------------------------------------
531 | ERROR | The behaviour of hexadecimal numeric strings was inconsistent prior to PHP 7 and support has been removed in PHP 7. Found: '0x7ff0000000000000'
533 | ERROR | The behaviour of hexadecimal numeric strings was inconsistent prior to PHP 7 and support has been removed in PHP 7. Found: '0xfffffffffffff'
---------------------------------------------------------------------------------------------------------------------------------------------------------------
Please, add an example of how to decode a custom public key
Hi,
Thanks for your nice job,
why this library has no CHOICE type ?
php 7.4 has been forked off from master, so travis regards 'nightly' as php8.0 now. according to this issue, it's possible to test on 7.4 by using the '7.4snapshot' version! https://travis-ci.community/t/add-php-7-4-branch-to-test-against/2179
Hello. Thanks for your project.
I have a problem, I'm trying to decrypt data about two certificates at once and I get an error.
My code:
. . .
$sign = "string has two cetrificate. an example of my data is below under the spoiler"
$binaryData = base64_decode($sign);
$seq = Sequence::fromDER($binaryData);
. . .
Error:
Fatal error: Uncaught Sop\ASN1\Exception\DecodeException: Length 3300 overflows data,
3279 bytes left. in /var/www/vendor/sop/asn1/lib/ASN1/Component/Length.php: 120
Stack trace:
#0 /var/www/vendor/sop/asn1/lib/ASN1/Type/Structure.php(317): Sop\ASN1\Component\Length: :expectFromDER()
#1 /var/www/vendor/sop/asn1/lib/ASN1/Element.php(209): Sop\ASN1\Type\Structure: :_decodeFromDER()
#2 /var/www/index.php(25): Sop\ASN1\Element: :fromDER()
#3 {main
}
thrown in <b>/var/vendor/sop/asn1/lib/ASN1/Component/Length.php</b> on line <b>120</b><br />
My base64 sign example:
p/s You may have problems parsing my ASN, because in my example Russian cryptography is used, then I adapted the code for correct parsing. But now I want to solve the problem described above
Hello,
I found out that "OIDs greater than 2.39 are not correclty decoded", e.g. "2.999"
Please find attached my small test program.
<?php
declare(strict_types=1);
require_once "vendor/autoload.php";
use ASN1\Element;
use ASN1\Type\Structure;
use ASN1\Type\UnspecifiedType;
use ASN1\Type\Constructed\Sequence;
use ASN1\Type\Primitive\Boolean;
use ASN1\Type\Primitive\NullType;
use ASN1\Type\Primitive\UTF8String;
use ASN1\Component\Identifier;
use ASN1\Type\Primitive\Integer;
use ASN1\Type\Tagged\ExplicitlyTaggedType;
use ASN1\Type\Primitive\ObjectIdentifier;
function oid_test($oidx="1.3.6") {
$seq = new Sequence(
new ExplicitlyTaggedType(
1, new ObjectIdentifier($oidx)
)
);
$der = $seq->toDER();
$seq = UnspecifiedType::fromDER($der)->asSequence();
if ($oidx == $seq->at(0)->asTagged()->asExplicit()->asObjectIdentifier()->oid()) {
echo "OK: $oidx\n";
} else {
echo "NOT OK: $oidx != ".$seq->at(0)->asTagged()->asExplicit()->asObjectIdentifier()->oid()."\n";
}
}
oid_test("1.3.6");
oid_test("1.3.6.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999991");
oid_test("2.1");
oid_test("2.49");
?>
Looks like this pattern is used throughout the codebase - I'll draft up a PR for this soon if I get a chance
eg:
/lib/ASN1/Element.php on line 213
/lib/ASN1/Component/Identifier.php on line 87
/lib/ASN1/Component/Length.php on line 52
Dear Developer,
The parser fails with the attached file, as it cannot parse indefinite length elements.
Here I read, the indefinite length elements are closed with 00 00
http://luca.ntop.org/Teaching/Appunti/asn1.html
So I fixed this with the following code:
public static function expectFromDER(...
if ($length->isIndefinite()) {
// throw new DecodeException("DER encoding must have definite length.");
$length= new Length(strpos($data, "\0\0", $idx) +2 -$idx, false); //$indefinite=false
Then it continues parsing elements with the correct length, until it reaches a NULL object: then it raises a new exception:
Fatal error: Uncaught UnexpectedValueException: Universal tag 0 not implemented.
Can you please fix the parser to be able to parse this file?
Thank you,
Gabor
The attached file is valid:
openssl pkcs7 -in signatureWithIdefiniteLength.pkcs7 -inform DER -print
Hi Joni!
I have an interesting example of weird DER code from the real life: Some insurance company uses CMS (Cryptographic Message Syntax) to exchange signed and encrypted data. Besides the indefinite-length encoding (which I managed using your latest release), I stumbled upon another irregularity, which I call "Constructed OCTET_STRING".
I have attached a minimal example file in DER format (gzipped) and the output of openssl-asn1parse.
constructed-octet-string.der.gz
constructed-octet-string.txt
Here is an excerpt from the parse output:
thalian@home ~ $ openssl asn1parse -in constructed-octet-string.der -inform DER
...
37:d=3 hl=2 l=inf cons: SEQUENCE
39:d=4 hl=2 l= 9 prim: OBJECT :pkcs7-data
50:d=4 hl=2 l=inf cons: cont [ 0 ]
52:d=5 hl=2 l=inf cons: OCTET STRING
54:d=6 hl=2 l= 8 prim: OCTET STRING :Test-001
64:d=6 hl=2 l= 8 prim: OCTET STRING :Test-002
74:d=6 hl=2 l= 0 prim: EOC
...
At index 52 there is the byte code 24 80
which sop/asn1 interpretes as "constructed, octet string" (as openssl does). But then it throws an exception in class PrimitiveString#39, because the isPrimitive check fails.
After this constructed octet string there are many primitive octet strings following (each with a size of 4096 byte), until the last octet string and the first EOC is found (the whole data file has ~1.3 MB), so the sense of this encoding seems to be a application-specific encoding of arbitrary-length strings with indefinite length, chunked into 4K packages.
I am looking for a possibility to let sop/asn1 concatenate these octet strings so that (in this example) the output is a single octet string "Test-001Test-002".
Hello,
I was checking the files on my server with PHP codefixer and I found following error in ElementDecodeTest.php line 72:
Function usage invokeArgs() (@call_with_passing_by_reference) is deprecated.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.