leithalnajjar / tlv_decoder

MIT License
2 stars 1 forks source link

Length encoding missing Len = 0x81 80 – 0x81 FF for lengths from 128 to 255 octets #1

Open reinies opened 1 year ago

reinies commented 1 year ago

Hey leithalnajjar,

I have found an issue in lib/src/tlv_utils.dart - method: static Uint8List _encodeLength(int length) There only is asked for length < 128. ( one octet). But it leaves out that there could be a size of 0x90 which would now converted as 0x82 00 90 instead DER rules 0x81 90.

So the method _encodeLength should be updated to the following:


  /// Convert length int to bytes
  static Uint8List _encodeLength(int length) {
    if (length < 128) {
      return Uint8List.fromList([length]);
    }
    if (length > 127 && length < 256) {
      var lengthBytes = Uint8List(2);
      lengthBytes[0] = 0x81;
      lengthBytes.setRange(1, 2, Uint8List.fromList([length]));
      return lengthBytes;
    }
    var lengthBytes = Uint8List(3);
    lengthBytes[0] = 0x82;
    lengthBytes.setRange(1, 3, Uint8List.fromList([length]));
    return lengthBytes;
  }

In TLV there is the encoding used form DER format:

DER the length fields are encoded as follows:

Best regards, Reinhard

leithalnajjar commented 1 year ago

Thanks, I will review the code and solve the problem as soon as possible