问题
I want to check if the given string to my function is plain text or base64 format. I am able to encode a plain text to base64 format and reverse it. But I could not figure out any way to validate if the string is already base64 format. Can anyone please suggest correct way of doing this in node js? Is there any API for doing this already available in node js.
回答1:
Encoding is byte level. If you're dealing in strings then all you can do is to guess or keep meta data information with your string to identify
But you can check these libraries out:
- https://www.npmjs.com/package/detect-encoding
- https://github.com/mooz/node-icu-charset-detector
回答2:
Valid base64 strings are a subset of all plain-text strings. Assuming we have a character string, the question is whether it belongs to that subset. One way is what Basit Anwer suggests. Those libraries require installing libicu though. A more portable way is to use the built-in Buffer:
Buffer.from(str, 'base64')
Unfortunately, this decoding function will not complain about non-Base64 characters. It will just ignore non-base64 characters. So, it alone will not help. But you can try encoding it back to base64 and compare the result with the original string:
Buffer.from(str, 'base64').toString('base64') === str
This check will tell whether str is pure base64 or not.
来源:https://stackoverflow.com/questions/32491681/how-to-check-if-a-string-is-plaintext-or-base64-format-in-node-js