encode method

Uint8List encode({
  1. ASN1EncodingRule encodingRule = ASN1EncodingRule.ENCODING_DER,
})

Encode the object to their byte representation.

encodingRule defines if the valueByteLength should be encoded as indefinite length (0x80) or fixed length with short/long form. The default is ASN1EncodingRule.ENCODING_DER which will automatically decode in definite length with short form.

Important note: Subclasses need to override this method and may call this method. If this method is called by a subclass, the subclass has to set the valueBytes before calling super.encode().

Implementation

Uint8List encode(
    {ASN1EncodingRule encodingRule = ASN1EncodingRule.ENCODING_DER}) {
  if (encodedBytes == null) {
    // Encode the length
    Uint8List lengthAsBytes;
    valueByteLength ??= valueBytes!.length;
    // Check if we have indefinite length or fixed length (short or longform)
    if (encodingRule ==
        ASN1EncodingRule.ENCODING_BER_CONSTRUCTED_INDEFINITE_LENGTH) {
      // Set length to 0x80
      lengthAsBytes = Uint8List.fromList([0x80]);
      // Add 2 to the valueByteLength to handle the 0x00, 0x00 at the end
      //valueByteLength = valueByteLength + 2;
    } else {
      lengthAsBytes = ASN1Utils.encodeLength(valueByteLength!,
          longform:
              encodingRule == ASN1EncodingRule.ENCODING_BER_LONG_LENGTH_FORM);
    }
    // Create the Uint8List with the calculated length
    encodedBytes = Uint8List(1 + lengthAsBytes.length + valueByteLength!);
    // Set the tag
    encodedBytes![0] = tag!;
    // Set the length bytes
    encodedBytes!.setRange(1, 1 + lengthAsBytes.length, lengthAsBytes, 0);
    // Set the value bytes
    encodedBytes!.setRange(
        1 + lengthAsBytes.length, encodedBytes!.length, valueBytes!, 0);
  }
  return encodedBytes!;
}