• Add random padding bytes to the passed value.

    This function can handle any number of value lengths and padding lengths as long as total output length is one byte larger than the original value (totalLength > value.length).

    Length information will also be stored within the padding bytes, so that the original value can be unpacked without needing additional information. You can simply unpack the original value with removePadding. Note that if value.length is very close to totalLength the added padding bytes are not random, because they are just the length information. (A padding of one byte will simply contain the information that 0 random padding bytes were added)

    Internals: This function does not store the value length, but the number of the added random bytes. This has the advantage, that you can always pad a value with a length of value.length to value.length + 1. When using the size of the value you would need more than one byte of additional information if the length of the value is larger than 256.

    The internal layout of the padding is this:

    | Field 1: extra flags(high 4 bits) length of field2 (lower four bits) | Field 2: length of field 3 | Field 3: padding (random) | Field 4: value |

    If Field 1 is zero, it means that Fields 2 and 3 do not exist. (Case when value.length = totalLength -1) If field 1 is 1 and field 2 is zero, it means that no field 3 exists. (Case when value.length = totalLength - 2)

    Examples:

    | value | totalLength | output bytes (r is random byte) | | | | F1 F2 F3 F4 | | 0x04 0x05 | 3 | 0x00 0x04 0x05 | | 0x04 0x05 | 4 | 0x01 0x00 0x04 0x05 | | 0x04 0x05 | 5 | 0x01 0x01 r 0x04 0x05 | | 0x04 0x05 | 6 | 0x01 0x02 rr 0x04 0x05 | | 0x04 0x05 | 258 | 0x01 0xFE r(254 times) 0x04 0x05 | | 0x04 0x05 | 259 | 0x01 0xFF r(255 times) 0x04 0x05 | | 0x04 0x05 | 260 | 0x02 0x00 0xFF r(255 times) 0x04 0x05 | | 0x04 0x05 | 261 | 0x02 0x01 0x00 r(256 times) 0x04 0x05 |

    Parameters

    • value: Uint8Array

      The value that shall be padded.

    • totalLength: number

      The length of the final padding. Note that this value needs to be at least 1 byte larger than value.length due to the byte that stores the padding length information.

    Returns Uint8Array