Skip to content
This repository was archived by the owner on Apr 22, 2023. It is now read-only.

Commit d5d5170

Browse files
committed
string_bytes: strip padding from base64 strings
Because of variations in different base64 implementation, it's been decided to strip all padding from the end of a base64 string and calculate its size from that.
1 parent f57ff78 commit d5d5170

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

src/string_bytes.cc

+7-8
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,15 @@ static inline size_t base64_decoded_size_fast(size_t size) {
6363
}
6464

6565
static inline size_t base64_decoded_size(const char* src, size_t size) {
66-
size = base64_decoded_size_fast(size);
66+
if (size == 0)
67+
return 0;
6768

68-
const char* end = src + size;
69-
// check for trailing padding (1 or 2 bytes)
70-
if (size > 0) {
71-
if (end[-1] == '=') size--;
72-
if (size > 0 && end[-2] == '=') size--;
73-
}
69+
if (src[size - 1] == '=')
70+
size--;
71+
if (size > 0 && src[size - 1] == '=')
72+
size--;
7473

75-
return size;
74+
return base64_decoded_size_fast(size);
7675
}
7776

7877

test/simple/test-buffer.js

+4
Original file line numberDiff line numberDiff line change
@@ -980,6 +980,10 @@ assert.throws(function() {
980980
}
981981
})();
982982

983+
// Make sure byteLength properly checks for base64 padding
984+
assert.equal(Buffer.byteLength('aaa=', 'base64'), 2);
985+
assert.equal(Buffer.byteLength('aaaa==', 'base64'), 3);
986+
983987
// Regression test for #5482: should throw but not assert in C++ land.
984988
assert.throws(function() {
985989
Buffer('', 'buffer');

0 commit comments

Comments
 (0)