From d5d5170c359fc96f36650cdd9b84cbb013c33735 Mon Sep 17 00:00:00 2001 From: Trevor Norris Date: Mon, 20 May 2013 12:35:31 -0700 Subject: [PATCH] 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. --- src/string_bytes.cc | 15 +++++++-------- test/simple/test-buffer.js | 4 ++++ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/string_bytes.cc b/src/string_bytes.cc index 5bf0a30..7ba2caf 100644 --- a/src/string_bytes.cc +++ b/src/string_bytes.cc @@ -63,16 +63,15 @@ static inline size_t base64_decoded_size_fast(size_t size) { } static inline size_t base64_decoded_size(const char* src, size_t size) { - size = base64_decoded_size_fast(size); + if (size == 0) + return 0; - const char* end = src + size; - // check for trailing padding (1 or 2 bytes) - if (size > 0) { - if (end[-1] == '=') size--; - if (size > 0 && end[-2] == '=') size--; - } + if (src[size - 1] == '=') + size--; + if (size > 0 && src[size - 1] == '=') + size--; - return size; + return base64_decoded_size_fast(size); } diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 20a6bdb..3808442 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -980,6 +980,10 @@ assert.throws(function() { } })(); +// Make sure byteLength properly checks for base64 padding +assert.equal(Buffer.byteLength('aaa=', 'base64'), 2); +assert.equal(Buffer.byteLength('aaaa==', 'base64'), 3); + // Regression test for #5482: should throw but not assert in C++ land. assert.throws(function() { Buffer('', 'buffer'); -- 2.7.4