0

I'm expecting isBase64('fooooooo'); or isBase64('12345678'); to return false since they are just a plain text.

How to differentiate between plain text and base64?

function isBase64(str) {
        const base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
        if (base64regex.test(str)) {
            return true;
        }
        return false;
}

console.log(isBase64('QmFzZTY0VGVzdA==')); // true
console.log(isBase64('0000'));             // true
console.log(isBase64('12345678'));         // true
console.log(isBase64('123456789'));        // false
console.log(isBase64('foo'));              // false
console.log(isBase64('fooooooo'));         // true
console.log(isBase64('bar'));              // false
console.log(isBase64('baaaaaar'));         // true
D3skDev
  • 61
  • 6
  • 2
    Does this answer your question? [Determine if string is in base64 using JavaScript](https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript) โ€“ Felipe Zavan Jun 21 '20 at 10:44
  • 2
    The problem is that `fooooooo`and `12345678` **are** valid Base64 strings, they are just not very likely ones (except if you want to require strict padding, which can find *some* cases, but not all as some Base64 strings end up not needing padding). โ€“ Joachim Sauer Jun 21 '20 at 10:47
  • 5
    base64 is a "plain text" representation of a binary structure. It could appear to be an English word. It could appear to be a sequence of numbers. It could appear to be gibberish. โ€“ James Jun 21 '20 at 10:57

1 Answers1

0

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. So, assuming them base64 string, if you try to decode them in any online editor, you will find some other characters, which means those character's base64 forms are 'fooooooo' and 12345678.

For example, trying to decode fooooooo gave me this result : '~(ยข('

One thing for sure is, base64 string does not contain space, so if you check for space in string and find any, that is not base64 string for sure, but if space is not found, there would be possibility for the string yet to be base64 string .

Mithu A Quayium
  • 729
  • 5
  • 14