Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 455
c g Avatar asked Sep 10 '15 01:09

c g


People also ask

How do you check whether a string is base64 encoded or not?

This works in Python: import base64 def IsBase64(str): try: base64. b64decode(str) return True except Exception as e: return False if IsBase64("ABC"): print("ABC is Base64-encoded and its result after decoding is: " + str(base64.

How do you check whether a string is base64 encoded or not JavaScript?

To determine if a string is a base64 string using JavaScript, we can check if a base64 string against a regex. For instance, we can write: const base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?

Is base64 a plaintext?

You are considering fooooooo and 12345678 plain text and not base64 string, while actually base64 encoded string itself is a plain text/string. Which means, fooooooo and 12345678 themselves are also base64 representation of some other strings.


1 Answers

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.

like image 74
Raul Santelices Avatar answered Sep 20 '22 15:09

Raul Santelices