0

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?

Dama Ramesh
  • 159
  • 14
  • The line of code that you have shown doesn't check if a string is encrypted. It just creates a new string that's decoded from Base64 (which is *not* an encryption). There is no simple method that will tell you whether a given text is encrypted or not as there are many possible encryption algorithms and non-encryption text manipulations. – RealSkeptic Jun 10 '19 at 07:41

2 Answers2

1

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

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 ....

green_dust
  • 47
  • 4