Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does not throw for invalid input characters #47

Open
webmaster128 opened this issue Jul 18, 2018 · 3 comments
Open

Does not throw for invalid input characters #47

webmaster128 opened this issue Jul 18, 2018 · 3 comments

Comments

@webmaster128
Copy link
Contributor

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 ]
@wmerfalen
Copy link

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...

@webmaster128
Copy link
Contributor Author

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.

@bookmoons
Copy link

bookmoons commented Sep 16, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants