yasna.rs icon indicating copy to clipboard operation
yasna.rs copied to clipboard

How to peek into DER and stop reading early?

Open zugzwang opened this issue 1 year ago • 1 comments

In some scenarios, I want to peek into a DER, parse an early element (think of an OID), and return it. It appears that I cannot do that with BERReader without reading the whole DER.

My best try was to ignore the remainder with the following

fn extract_oid(der: &[u8]) {
    let oid = yasna::parse_der(der, |r| {
        // Let's say we have a SEQUENCE
        r.read_sequence(|r| {
            // The OID I want is embedded inside an inner SEQUENCE:
            let oid = r.next().read_sequence(|r| {
                let oid = r.next().read_oid()?;
                let _remainder = r.next().read_der(); // Ignore the remainder of that sequence
                Ok(oid)
            })?;
            let _remainder = r.next().read_der(); // Ignore the rest of the sequence
            Ok(oid)
        })
    });
    println!("extracted OID {:?}", oid);
}

Without checking the remainder, yasna fails with Err(ASN1Error { kind: Extra }), and I would like to ignore this error.

zugzwang avatar May 09 '23 18:05 zugzwang