4

I am not sure how to check if a String is Base64 encoded or not using android.Base64. I know in standard Java using java.util.Base64 calling Base64.getDecoder().decode() would through an IllegalArgumentException if the String wasn't already in Base64, but on android I get no such error, so how can I check if it is Base64 encoded?

Soggy_Toast
  • 57
  • 1
  • 9
  • Fair warning: just because a string _can_ be decoded with Base64 does not mean it was actually encoded with Base64 or will produce meaningful output. – Louis Wasserman Oct 18 '17 at 04:19
  • 2
    Possible duplicate of [How to check whether the string is base64 encoded or not](https://stackoverflow.com/questions/8571501/how-to-check-whether-the-string-is-base64-encoded-or-not) – Northern Poet Oct 18 '17 at 04:23
  • @LouisWasserman I know that, but I would like to know if the String is able to be decoded. If not I want an error to be thrown or some indication that it couldn't be decoded. – Soggy_Toast Oct 18 '17 at 05:33
  • @Miller This didn't work for me, or maybe I didn't apply it correctly. – Soggy_Toast Oct 18 '17 at 05:34
  • What is your string, that can't be checked using common code? – Northern Poet Oct 18 '17 at 05:36
  • Not a specific string, but for example: if I try to decode the String "this-is-a-test" I should get an error because "-" is not part of the Base64 scheme, but I don't get any errors or indication that what was asked to be decoded was not in fact a valid input. – Soggy_Toast Oct 18 '17 at 05:47
  • @Miller Nevermind, I apologize. I was implementing it incorrectly but have now fixed it. – Soggy_Toast Oct 18 '17 at 06:04

2 Answers2

1

Add to Gradle:

implementation 'commons-codec:commons-codec:1.9'

Add to your code:

if (Base64.isBase64(yourString)) {
   //do stuff
} else {
   //do other stuff
}
darkknightsds
  • 530
  • 8
  • 16
  • I am getting `No static method isBase64(Ljava/lang/String;)Z in class Lorg/apache/commons/codec/binary/Base64; or its super classes` – hiddeneyes02 Jun 09 '20 at 19:58
-2

try this:

   try{
     Base64.encode("thestringyouwanttocheck".getBytes(),Base64.DEFAULT);
   }catch(IllegalArgumentException e){
      Toast toast=Toast.makeText(context,"Illigal Input",duration);
      toast.show();
   }