base64-js
base64-js copied to clipboard
Does not throw for invalid input characters
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 ]
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...
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.
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