How to check if a String is encoded in base64?

2

I'm working on an email application using VueJs / Quasar on the client and HapiJS on the server, and some emails (depending on the sender) come with base64-encoded text, and some do not.

To solve this, I need to find a way to identify if the email body is in base64 and only after identifying it to send it decoded to the client, and if it is not encrypted, just send it to the client

    
asked by anonymous 24.08.2017 / 17:00

1 answer

4

You can use regular expression to check whether a string is base64-encoded or not:

^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$

Example:

var base64 = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;

base64.test("Ola1234345345");             // retorna false
base64.test("ZXdyd2Vyd2Vyd2VycXJxd2VycXdlcnF3ZXJxd2VyZXdxcg==");   // retorna true

or you can use a simple function:

function isBase64(str) {
    try {
        return btoa(atob(str)) == str;
    } catch (err) {
        return false;
    }
}
    
24.08.2017 / 17:06