Buffer.from(' ???', 'base64')
This code returns an empty buffer instead of throwing an error, which is the expected behaviour. What is the correct way of verifying the validity of encoded data and decoding it in nodejs?
There seems to be nothing in the nodejs 12.16 docs about an error being thrown if the characters in a given string are not part of the encoding specified.
In fact, a small experiment seems to suggest that Buffer.from()
simply ignores such characters that do not belong in the encoding.
try{
const str1 = "ai?73";
const str2 = "ai73";
const str3 = "??a?i73??";
const encoded1 = Buffer.from(str1,'base64').toString('base64');
const encoded2 = Buffer.from(str2,'base64').toString('base64');
const encoded3 = Buffer.from(str3,'base64').toString('base64');
console.log(`On base64 encoding ${str1}: ${encoded1}`);
console.log(`On base64 encoding ${str2}: ${encoded2}`);
console.log(`On base64 encoding ${str3}: ${encoded3}`);
}catch(e){
console.error(`ERROR:`,e);
}
It yields the following output:
On base64 encoding ai?73: ai73
On base64 encoding ai73: ai73
On base64 encoding ??a?i73??: ai73
So, your best bet would be to use a package like is-base64, as suggested by user dajnz in the comments.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments