Skip to content

Incorrect decode with wrapped text #4

@ceztko

Description

@ceztko

I noticed the library fails with base64 encoded wrapped text (typically column text). Wrapped text can be obtained for example by using this online tool and clicking "Split lines into 76 character wide chunks", I fixed it by improving DecodeLength function and skipping newlines also in Decode. I changed the code a bit to adapt to my tastes but it should give the idea of what is needed to fix it:

size_t DecodedLength(const char *str, size_t len)
{
    size_t numEq = 0;
    size_t size = 0;

    for (size_t i = 0; i < len; i++) {
        char ch = str[i];
        if (ch == '\n' || ch == '\r')
            continue;

        if (ch == '=')
            numEq++;

        size++;
    }

    return ((6 * size) / 8) - numEq;
}

bool Decode(const char *str, size_t len, std::string &out)
{
    int i = 0, j = 0;
    size_t dec_len = 0;
    unsigned char a3[3];
    unsigned char a4[4];

    out.resize(DecodedLength(str, len));

    while (len--) {
        char ch = *str;
        if (ch == '=') {
            break;
        }

        if (ch == '\n' || ch == '\r') {
            str++;
            continue;
        }

        a4[i++] = *(str++);
        if (i == 4) {
            for (i = 0; i < 4; i++) {
                a4[i] = b64_lookup(a4[i]);
            }

            a4_to_a3(a3, a4);

            for (i = 0; i < 3; i++) {
                out[dec_len++] = a3[i];
            }

            i = 0;
        }
    }

    if (i) {
        for (j = i; j < 4; j++) {
            a4[j] = '\0';
        }

        for (j = 0; j < 4; j++) {
            a4[j] = b64_lookup(a4[j]);
        }

        a4_to_a3(a3, a4);

        for (j = 0; j < i - 1; j++) {
            out[dec_len++] = a3[j];
        }
    }

    return (dec_len == out.size());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions