package org.cryptonit;

import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.Util;

/**
 * @author Mathias Brossard
 */
public class BERTLV {
    final private byte [] buffer;
    final private short end;
    private short current;

    public BERTLV(byte[] buffer, short begin, short end) {
        this.buffer = buffer;
        this.current = begin;
        this.end = end;
    }

    public short readLength() {
        short s = (short) buffer[current];
        current += 1;

        return s;
    }

    public static short decodeLength(byte[] buf, short offset) {
        short off = offset;
        byte b = buf[off];
        short s = buf[off];
        if ((b & (byte) 0x80) != 0) {
            off += 1;

            if (b == (byte) 0x81) {
                s = (short) (0x00FF & buf[off]);
            } else if (b == (byte) 0x82) {
                s = Util.getShort(buf, off);
            } else {
                ISOException.throwIt(ISO7816.SW_UNKNOWN);
            }
        }
        return s;
    }
}

@@ -452,24 +452,58 @@
 dLength() %7B%0A
+        byte b = buffer%5Bcurrent%5D;%0A
         shor
@@ -548,32 +548,695 @@
  current += 1;%0A%0A
+        if ((b & (byte) 0x80) != 0) %7B%0A            if (b == (byte) 0x81) %7B%0A                if (current %3E= end) %7B%0A                    ISOException.throwIt(ISO7816.SW_DATA_INVALID);%0A                %7D%0A                s = (short) (0x00FF & buffer%5Bcurrent%5D);%0A                this.current += 1;%0A            %7D else if (b == (byte) 0x82) %7B%0A                if (current %3E= (short) (end + 1)) %7B%0A                    ISOException.throwIt(ISO7816.SW_DATA_INVALID);%0A                %7D%0A                s = Util.getShort(buffer, current);%0A                this.current += 2;%0A            %7D else %7B%0A                ISOException.throwIt(ISO7816.SW_DATA_INVALID);%0A            %7D%0A        %7D%0A
         return s

Add support for longer length encoding