How to check if a string is plaintext or base64 format in Node.js

北战南征 提交于 2019-12-22 04:05:21

问题


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:

  1. https://www.npmjs.com/package/detect-encoding
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!