From: Feross Aboukhadijeh Date: Sun, 29 Jun 2014 15:29:43 +0000 (-0700) Subject: Strip invalid characters from base64 strings (fix #33) X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=1f03ea87f7e4d1c5a1b154419efefb704281dd2a;p=buffer.git Strip invalid characters from base64 strings (fix #33) --- diff --git a/index.js b/index.js index 533f8f0..9526e88 100644 --- a/index.js +++ b/index.js @@ -53,13 +53,8 @@ function Buffer (subject, encoding, noZero) { var type = typeof subject - // Workaround: node's base64 implementation allows for non-padded strings - // while base64-js does not. if (encoding === 'base64' && type === 'string') { - subject = stringtrim(subject) - while (subject.length % 4 !== 0) { - subject = subject + '=' - } + subject = base64clean(subject) } // Find the length @@ -1016,6 +1011,18 @@ Buffer._augment = function (arr) { return arr } +var INVALID_BASE64_RE = /[^+\/0-9A-z]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '')