static int parse_asn1_length()

in native/src/sslutils.c [553:598]


static int parse_asn1_length(unsigned char **asn1, int *len) {

    /* Length immediately follows tag so increment before reading first (and
     * possibly only) length byte.
     */
    (*asn1)++;

    if (**asn1 & 0x80) {
        // MSB set. Remaining bits are number of bytes used to store the length.
        int i, l;

        // How many bytes for this length?
        i = **asn1 & 0x7F;

        if (i == 0) {
            /* This is the indefinite form of length. Since certificates use DER
             * this should never happen and is therefore an error.
             */
            return 1;
        }
        if (i > 3) {
            /* Three bytes for length gives a maximum of 16MB which should be
             * far more than is required. (2 bytes is 64K which is probably more
             * than enough but play safe.)
             */
            return 1;
        }

        // Most significant byte is first
        l = 0;
        while (i > 0) {
            l <<= 8;
            (*asn1)++;
            l += **asn1;
            i--;
        }
        *len = l;
    } else {
        // Single byte length
        *len = **asn1;
    }

    (*asn1)++;

    return 0;
}