Skip to content

base64::encode crashes for small buffers #4921

Closed
@LaborEtArs

Description

@LaborEtArs

String base64::encode(uint8_t * data, size_t length, bool doNewLines) will crash when used with a quite short input buffer; for example 4 bytes.
A 4 byte input to base64 will produce an 8 byte output (plus trailing '\0' = 9), as two filling bytes will by attached to the input before processing. The buffer calculated by base64::encode however is only 4 * 1.6f + 1 = 6.4 + 1 = 6 + 1 = 7 bytes long!
A better size algorithm would be:
size_t size = ((((length * 4) + 2) / 3) + (3 - (length % 3)) + 1); if (doNewLines) size += ((size + 71) / 72);

(((length * 4) + 2) / 3):
3 input bytes (24 bits) will be converted to 4 output bytes (4 * 6bits = 24bit); the +2 ensures the division to be the next ceiling integer

(3 - (length % 3)):
Input buffers that can't be divided by 3 will be filled up by the algorithm

1:
Trailing '\0'

((size + 71) / 72):
If 'doNewLines' is true, every 72 (encoded) chars a newline will be added (again the +71 ensures the division to be the next ceiling integer)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions