Dama Ramesh
Dama Ramesh

Reputation: 169

How to check if a input string is encoded or not?

I am trying to check my input string is already encoded or not. But getting "true" for "123456", "admin123".

new String(Base64.getDecoder().decode(inputStr), StandardCharsets.UTF_8);
public class AppTest {

    public static void main(String[] args) {
        String inputStr = "admin123";
        System.out.println("isEncoded: " + isEncoded(inputStr));
    }

    private static boolean isEncoded(String inputStr) {
        try {
            new String(Base64.getDecoder().decode(inputStr), StandardCharsets.UTF_8);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

Could you please help me to check any alternate code to check my input string either encoded or not?

Upvotes: 0

Views: 2246

Answers (2)

green_dust
green_dust

Reputation: 47

base64 is not an encryption its an encoding algorithm used to convert binary data into compact text format so you can send it through text based protocols puls base64 is not invented to encode text (character binary data) you use it with pictures videos ....

Upvotes: 0

GhostCat
GhostCat

Reputation: 140437

Base64 is not about encryption. It is about encoding. Base64 doesn't turn your input into something that you can only decrypt when you know some secret key. No, the purpose of Base64 encoding is to ensure that binary information can safely be represented as ASCII charset (see here for more details). Sometimes Base64 is used together with encryption: you first encrypt a message, then you encode it with Base64: because sending ASCII chars over a network is less complicated compared to sending arbitrary binary data.

Now: your two strings "123456" and "admin123" are solely using ASCII characters, thus encoding with Base64 is pointless. Or to be precise: because "all ASCII", decoding will not throw an error.

So: your method isEncrypted() should thus be renamed isEncoded(). And as RealSkeptic correctly points out, the decode() method will (only) throw an InvalidArgumentException when the input string is not in Base64. ( assuming we are talking about the "built-in" Base64.Decoder class )

But as said, the two example strings are pure ASCII, therefore decoding will not give you an error, and you always end up with result true.

The question "is a string base64 encoded" is answered here by the way.

Upvotes: 1

Related Questions