Greetings, everyone!
While working on an extension I've found an error in how length of
encoded base64 string is calulated;
This error is present in 3 files across all supported versions:
/src/common/base64.c, function pg_b64_enc_len;
/src/backend/utils/adt/encode.c, function pg_base64_enc_len;
/contrib/pgcrypto/pgp-armor.c, function pg_base64_enc_len (copied from
encode.c).
In all three cases the length is calculated as follows:
(srclen + 2) * 4 / 3; (plus linefeed in latter two cases)
There's also a comment /* 3 bytes will be converted to 4 */
This formula is wrong. Let's calculate encoded length for different
starting lengths:
starting length 2: (2 + 2) * 4 / 3 = 5,
starting length 3: (3 + 2) * 4 / 3 = 6,
starting length 4: (4 + 2) * 4 / 3 = 8,
starting length 6: (6 + 2) * 4 / 3 = 10,
starting length 10: (10 + 2) * 4 / 3 = 16,
when it should be 4, 4, 8, 8, 16.
So the suggestion is to change the formula to a right one: (srclen + 2)
/ 3 * 4;
The patch is attached.
Oleg Tselebrovskiy, Postgres Pro