How to verify if a String is encoded in Base64?

Asked

Viewed 1,087 times

2

I am working on an email application using Vuejs/Quasar on the client and Hapijs on the server, and some emails (depends on the sender) comes with the text encoded in Base64, and others not.

Here comes the problem, to solve this I need to find a way to identify if the email body is in Base64 and only after identifying it sent decoded to the customer, and if it is not encrypted only send to the customer

  • 4

    Base64 should not be used for encryption, as it does not hide information

  • I get it, I still don’t know much this Base64 business, just know that some emails come in Base64 and others not...

  • I think this is a good reading: https://answall.com/q/162369/64969

  • 1

    So in my case, I’m not encrypting, I’m just coding so that the information can be read by any system, right??

  • 1

    That’s right. Base64 emerged in the context of email to mainly do the transfer of binary attachments files. In this case, it was a protocol limitation that only allowed printable ASCII characters, spacing is line breaks

  • 1

    Okay then, thank you so much for the clarification and help @Jefferson Quesado

Show 1 more comment

1 answer

5


You can use regular expression to check whether a string is encoded in Base64 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;
    }
}
  • 1

    Thank you so much for helping @13dev... Saved me hours of research

Browser other questions tagged

You are not signed in. Login or sign up in order to post.