base64-js icon indicating copy to clipboard operation
base64-js copied to clipboard

Does not throw for invalid input characters

Open webmaster128 opened this issue 7 years ago • 3 comments

A valid base64 input length including characters not in the base64 alphabet lead to wrong outputs instead of an exception. E.g.

$ node
> var base64js = require('base64-js')
> base64js.toByteArray("aaaä")
Uint8Array [ 105, 166, 128 ]
> base64js.toByteArray("aaa}")
Uint8Array [ 105, 166, 128 ]

webmaster128 avatar Jul 18 '18 08:07 webmaster128

Don't quote me on this, but I think the right direction to take to fixing this would be to see how to handle utf-8 character sequences...

wmerfalen avatar Sep 12 '18 08:09 wmerfalen

I think the right direction to take to fixing this would be to see how to handle utf-8 character sequences...

The input is a JavaScript string, which is a list of unicode codepoints that has no encoding. This string must only contain the characters a-z, A-Z, 0-9, +, /, = and everything else is no valid base64 encoding. So the problem is entirely unrelated to UTF-8.

webmaster128 avatar Sep 16 '18 10:09 webmaster128

Simple validation function if anyone wants to pop it in before decode. Supports all alphabets base64-js does.

/**
 * Validate base64 string.
 *
 * Throws error if validation fails.
 * Returns without error if validation succeeds.
 *
 * @param {string} string - String to validate.
 *
 * @throws {Error} If string is not valid base64. Message 'invalid base64'.
 */
function validateBase64 (string) {
  const format = /^[a-zA-Z0-9+/_-]*={0,2}$/
  const valid = format.test(string)
  if (!valid) throw new Error('invalid base64')
}

It catches both cases in the OP.

validateBase64('') // Pass
validateBase64('AQID') // Pass
validateBase64('AQIDBA==') // Pass
validateBase64('aaa}') // FAIL
validateBase64('aaaä') // FAIL

bookmoons avatar Sep 16 '18 21:09 bookmoons