How to check whether a string is base64 encoded or not












157















I want to decode a base64 encoded string, then store it in my database. If the input is not base64 encoded, I need to throw an error. How can I check if the string was base64 enocoded?










share|improve this question

























  • Why? How can the situation arise?

    – user207421
    Oct 9 '15 at 9:25






  • 1





    without specifying which programming language (and/or) Operating System you are targeting, this is a very open question

    – bcarroll
    Jan 5 '16 at 16:32






  • 3





    All that you can determine is that the string contains only characters that are valid for a base64 encoded string. It may not be possible to determine that the string is the base64 encoded version of some data. for example test1234 is a valid base64 encoded string, and when you decode it you will get some bytes. There is no application independent way of concluding that test1234 is not a base64 encoded string.

    – Kinjal Dixit
    Feb 10 '16 at 11:56
















157















I want to decode a base64 encoded string, then store it in my database. If the input is not base64 encoded, I need to throw an error. How can I check if the string was base64 enocoded?










share|improve this question

























  • Why? How can the situation arise?

    – user207421
    Oct 9 '15 at 9:25






  • 1





    without specifying which programming language (and/or) Operating System you are targeting, this is a very open question

    – bcarroll
    Jan 5 '16 at 16:32






  • 3





    All that you can determine is that the string contains only characters that are valid for a base64 encoded string. It may not be possible to determine that the string is the base64 encoded version of some data. for example test1234 is a valid base64 encoded string, and when you decode it you will get some bytes. There is no application independent way of concluding that test1234 is not a base64 encoded string.

    – Kinjal Dixit
    Feb 10 '16 at 11:56














157












157








157


47






I want to decode a base64 encoded string, then store it in my database. If the input is not base64 encoded, I need to throw an error. How can I check if the string was base64 enocoded?










share|improve this question
















I want to decode a base64 encoded string, then store it in my database. If the input is not base64 encoded, I need to throw an error. How can I check if the string was base64 enocoded?







base64






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 30 '18 at 8:38









anothernode

2,792102643




2,792102643










asked Dec 20 '11 at 6:16









loganathanloganathan

2,23362537




2,23362537













  • Why? How can the situation arise?

    – user207421
    Oct 9 '15 at 9:25






  • 1





    without specifying which programming language (and/or) Operating System you are targeting, this is a very open question

    – bcarroll
    Jan 5 '16 at 16:32






  • 3





    All that you can determine is that the string contains only characters that are valid for a base64 encoded string. It may not be possible to determine that the string is the base64 encoded version of some data. for example test1234 is a valid base64 encoded string, and when you decode it you will get some bytes. There is no application independent way of concluding that test1234 is not a base64 encoded string.

    – Kinjal Dixit
    Feb 10 '16 at 11:56



















  • Why? How can the situation arise?

    – user207421
    Oct 9 '15 at 9:25






  • 1





    without specifying which programming language (and/or) Operating System you are targeting, this is a very open question

    – bcarroll
    Jan 5 '16 at 16:32






  • 3





    All that you can determine is that the string contains only characters that are valid for a base64 encoded string. It may not be possible to determine that the string is the base64 encoded version of some data. for example test1234 is a valid base64 encoded string, and when you decode it you will get some bytes. There is no application independent way of concluding that test1234 is not a base64 encoded string.

    – Kinjal Dixit
    Feb 10 '16 at 11:56

















Why? How can the situation arise?

– user207421
Oct 9 '15 at 9:25





Why? How can the situation arise?

– user207421
Oct 9 '15 at 9:25




1




1





without specifying which programming language (and/or) Operating System you are targeting, this is a very open question

– bcarroll
Jan 5 '16 at 16:32





without specifying which programming language (and/or) Operating System you are targeting, this is a very open question

– bcarroll
Jan 5 '16 at 16:32




3




3





All that you can determine is that the string contains only characters that are valid for a base64 encoded string. It may not be possible to determine that the string is the base64 encoded version of some data. for example test1234 is a valid base64 encoded string, and when you decode it you will get some bytes. There is no application independent way of concluding that test1234 is not a base64 encoded string.

– Kinjal Dixit
Feb 10 '16 at 11:56





All that you can determine is that the string contains only characters that are valid for a base64 encoded string. It may not be possible to determine that the string is the base64 encoded version of some data. for example test1234 is a valid base64 encoded string, and when you decode it you will get some bytes. There is no application independent way of concluding that test1234 is not a base64 encoded string.

– Kinjal Dixit
Feb 10 '16 at 11:56












18 Answers
18






active

oldest

votes


















194














You can use the following regular expression to check if a string is base64 encoded or not:



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


In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /]. If the rest length is less than 4, the string is padded with '=' characters.



^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.



([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$ means the string ends in one of three forms: [A-Za-z0-9+/]{4}, [A-Za-z0-9+/]{3}= or [A-Za-z0-9+/]{2}==.






share|improve this answer





















  • 6





    Just wanted to verify so please help with my question : What is the guarantee that this regex will always refers to only base64 string?? If there is any string having no space and it is multiple of 4 characters, then will that string be considered as base64 string????

    – DShah
    Oct 1 '12 at 10:11








  • 3





    Then it is a valid base64 string which can be decoded. You could add a minimum length constraint; for example, instead of zero or more repetitions of groups of four, require (say) four or more. It depends on your problem, too; if your users often enter a single word in a language with long words and pure ASCII (Hawaiian?) it's more error-prone than if non-base64 input typically contains spaces, punctuation, etc.

    – tripleee
    Nov 22 '12 at 21:43













  • @Didier Ghys it seems this base64 encoded string IHRlc3QgbWVzc2FnZQoK does not much the regex. Or maybe it is not base64 encoded ? though base64_decode('IHRlc3QgbWVzc2FnZQoK') outputs write string - test message

    – dav
    Dec 24 '12 at 8:32






  • 51





    This only tell that an input could have been a b64 encoded value, but it does not tell whether or not the input is actually a b64 encoded value. In other words, abcd will match, but it is not necessarily represent the encoded value of rather just a plain abcd input

    – Tzury Bar Yochay
    May 19 '13 at 10:10






  • 3





    Your regexp is incorrect, since it does not match the empty string, with is the base64 encoding of zero-length binary data according to RFC 4648.

    – reddish
    Feb 19 '17 at 16:53



















42














If you are using Java, you can actually use commons-codec library



import org.apache.commons.codec.binary.Base64;

String stringToBeChecked = "...";
boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());





share|improve this answer



















  • 13





    from the documentation: isArrayByteBase64(byte arrayOctet) Deprecated. 1.5 Use isBase64(byte), will be removed in 2.0.

    – Avinash R
    Dec 5 '13 at 4:32








  • 6





    You can use also Base64.isBase64(String base64) instead of converting it to byte array yourself.

    – Sasa
    Feb 27 '14 at 12:00








  • 5





    Sadly, based on documentation: commons.apache.org/proper/commons-codec/apidocs/org/apache/… : "Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid." This means that this methods has some false positives like "whitespace" or numbers ("0", "1").

    – Christian Vielma
    Feb 2 '15 at 19:23











  • for string Base64.isBase64(content)

    – ema
    Feb 25 '16 at 17:17






  • 1





    This answer is wrong because given stringToBeChecked="some plain text" then it sets boolean isBase64=true even though it's not a Base64 encoded value. Read the source for commons-codec-1.4 Base64.isArrayByteBase64() it only checks that each character in the string is valid to be considered for Base64 encoding and allows white space.

    – Brad
    Apr 27 '17 at 11:30





















39














Well you can:




  • Check that the length is a multiple of 4 characters

  • Check that every character is in the set A-Z, a-z, 0-9, +, / except for padding at the end which is 0, 1 or 2 '=' characters


If you're expecting that it will be base64, then you can probably just use whatever library is available on your platform to try to decode it to a byte array, throwing an exception if it's not valid base 64. That depends on your platform, of course.






share|improve this answer































    11














    Try like this for PHP5



    //where $json is some data that can be base64 encoded
    $json=some_data;

    //this will check whether data is base64 encoded or not
    if (base64_decode($json, true) == true)
    {
    echo "base64 encoded";
    }
    else
    {
    echo "not base64 encoded";
    }





    share|improve this answer


























    • why -1. Its working fine for me

      – Suneel Kumar
      Dec 10 '13 at 8:08






    • 1





      Which language is this? The question was asked without referring to a language

      – Ozkan
      Nov 27 '14 at 10:53











    • @Ozkan its in php5

      – Suneel Kumar
      Nov 27 '14 at 14:03











    • this will not work. read the docs Returns FALSE if input contains character from outside the base64 alphabet. base64_decode

      – Aley
      Apr 30 '16 at 21:29











    • How? if input contains outside character then it is not base64, right?

      – Suneel Kumar
      Feb 1 '17 at 13:16



















    6














    As of Java 8, you can simply use java.util.Base64 to try and decode the string:



    String someString = "...";
    Base64.Decoder decoder = Base64.getDecoder();

    try {
    decoder.decode(someString);
    } catch(IllegalArgumentException iae) {
    // That string wasn't valid.
    }





    share|improve this answer



















    • 1





      yes, it's an option, but don't forget that catch is quite expensive operation in Java

      – panser
      Dec 28 '17 at 22:45



















    4














    There are many variants of Base64, so consider just determining if your string resembles the varient you expect to handle. As such, you may need to adjust the regex below with respect to the index and padding characters (i.e. +, /, =).



    class String
    def resembles_base64?
    self.length % 4 == 0 && self =~ /^[A-Za-z0-9+/=]+Z/
    end
    end


    Usage:



    raise 'the string does not resemble Base64' unless my_string.resembles_base64?





    share|improve this answer































      4














      Check to see IF the string's length is a multiple of 4. Aftwerwards use this regex to make sure all characters in the string are base64 characters.



      A[a-zA-Zd/+]+={,2}z



      If the library you use adds a newline as a way of observing the 76 max chars per line rule, replace them with empty strings.






      share|improve this answer


























      • The link mentioned shows 404. Please check and update.

        – Ankur
        Jul 9 '14 at 10:16











      • Sorry @AnkurKumar but that's what happen when people have uncool URLs: they change all the time. I have no idea where it's moved to. I hope you find other useful resources through Google

        – Yaw Boakye
        Jul 13 '14 at 2:41











      • You can always get old pages from web.archive.org - here's the original url. web.archive.org/web/20120919035911/http://… or I posted the text here: gist.github.com/mika76/d09e2b65159e435e7a4cc5b0299c3e84

        – Mladen Mihajlovic
        Jun 16 '18 at 11:52



















      4














      var base64Rejex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=|[A-Z0-9+/]{4})$/i;
      var isBase64Valid = base64Rejex.test(base64Data); // base64Data is the base64 string

      if (isBase64Valid) {
      // true if base64 formate
      console.log('It is base64');
      } else {
      // false if not in base64 formate
      console.log('it is not in base64');
      }





      share|improve this answer

































        1














        Try this:



        public void checkForEncode(String string) {
        String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(string);
        if (m.find()) {
        System.out.println("true");
        } else {
        System.out.println("false");
        }
        }





        share|improve this answer


























        • consider providing an explanation to your code

          – arghtype
          Oct 28 '15 at 17:38



















        1














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


        this regular expression helped me identify the base64 in my application in rails, I only had one problem, it is that it recognizes the string "errorDescripcion", I generate an error, to solve it just validate the length of a string.






        share|improve this answer


























        • The above regex /^.....$/.match(my_string) gives formatting error by saying 'Unmatched closing )'

          – james2611nov
          May 17 '18 at 14:57











        • And with 'premature end of char-class: /^(([A-Za-z0-9+/' syntax errors.

          – james2611nov
          May 17 '18 at 15:22











        • Nevermind fixed it by adding in front of every / character.

          – james2611nov
          May 17 '18 at 15:28











        • errorDescription is a valid base64 string, it decodes into the binary sequence of bytes (in hex): 7a ba e8 ac 37 ac 72 b8 a9 b6 2a 27.

          – Luis Colorado
          Nov 22 '18 at 9:03



















        1














        C#
        This is performing great:



        static readonly Regex _base64RegexPattern = new Regex(BASE64_REGEX_STRING, RegexOptions.Compiled);

        private const String BASE64_REGEX_STRING = @"^[a-zA-Z0-9+/]*={0,3}$";

        private static bool IsBase64(this String base64String)
        {
        var rs = (!string.IsNullOrEmpty(base64String) && !string.IsNullOrWhiteSpace(base64String) && base64String.Length != 0 && base64String.Length % 4 == 0 && !base64String.Contains(" ") && !base64String.Contains("t") && !base64String.Contains("r") && !base64String.Contains("n")) && (base64String.Length % 4 == 0 && _base64RegexPattern.Match(base64String, 0).Success);
        return rs;
        }





        share|improve this answer


























        • Console.WriteLine("test".IsBase64()); // true

          – Langdon
          Sep 7 '18 at 20:32













        • Recommend to switch programming language to solve a problem is in general not a valid response.

          – Luis Colorado
          Nov 22 '18 at 9:04



















        0














        There is no way to distinct string and base64 encoded, except the string in your system has some specific limitation or identification.






        share|improve this answer































          0














          This snippet may be useful when you know the length of the original content (e.g. a checksum). It checks that encoded form has the correct length.



          public static boolean isValidBase64( final int initialLength, final String string ) {
          final int padding ;
          final String regexEnd ;
          switch( ( initialLength ) % 3 ) {
          case 1 :
          padding = 2 ;
          regexEnd = "==" ;
          break ;
          case 2 :
          padding = 1 ;
          regexEnd = "=" ;
          break ;
          default :
          padding = 0 ;
          regexEnd = "" ;
          }
          final int encodedLength = ( ( ( initialLength / 3 ) + ( padding > 0 ? 1 : 0 ) ) * 4 ) ;
          final String regex = "[a-zA-Z0-9/\+]{" + ( encodedLength - padding ) + "}" + regexEnd ;
          return Pattern.compile( regex ).matcher( string ).matches() ;
          }





          share|improve this answer































            0














            If the RegEx does not work and you know the format style of the original string, you can reverse the logic, by regexing for this format.



            For example I work with base64 encoded xml files and just check if the file contains valid xml markup. If it does not I can assume, that it's base64 decoded. This is not very dynamic but works fine for my small application.






            share|improve this answer































              0














              This works in Python:



              def is_base64(string):
              if len(string) % 4 == 0 and re.test('^[A-Za-z0-9+/=]+Z', string):
              return(True)
              else:
              return(False)





              share|improve this answer































                0














                This works in Python:



                import base64

                def IsBase64(str):
                try:
                base64.b64decode(str)
                return True
                except Exception as e:
                return False

                if IsBase64("ABC"):
                print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
                else:
                print("ABC is NOT Base64-encoded.")

                if IsBase64("QUJD"):
                print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
                else:
                print("QUJD is NOT Base64-encoded.")


                Summary: IsBase64("string here") returns true if string here is Base64-encoded, and it returns false if string here was NOT Base64-encoded.






                share|improve this answer































                  0














                  It is impossible to check if a string is base64 encoded or not. It is only possible to validate if that string is of a base64 encoded string format, which would mean that it could be a string produced by base64 encoding (to check that, string could be validated against a regexp or a library could be used, many other answers to this question provide good ways to check this, so I won't go into details).



                  For example, string flow is a valid base64 encoded string. But it is impossible to know if it is just a simple string, an English word flow, or is it base 64 encoded string ~Z0






                  share|improve this answer































                    -1














                    Try this using a previously mentioned regex:



                    String regex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                    if("TXkgdGVzdCBzdHJpbmc/".matches(regex)){
                    System.out.println("it's a Base64");
                    }


                    ...We can also make a simple validation like, if it has spaces it cannot be Base64:



                    String myString = "Hello World";
                    if(myString.contains(" ")){
                    System.out.println("Not B64");
                    }else{
                    System.out.println("Could be B64 encoded, since it has no spaces");
                    }





                    share|improve this answer


























                    • Ok, could you please give a solution then?

                      – Marco
                      Jan 17 at 16:08











                    • working on it :)

                      – HIRA THAKUR
                      Jan 18 at 6:45











                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    autoActivateHeartbeat: false,
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8571501%2fhow-to-check-whether-a-string-is-base64-encoded-or-not%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    18 Answers
                    18






                    active

                    oldest

                    votes








                    18 Answers
                    18






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    194














                    You can use the following regular expression to check if a string is base64 encoded or not:



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


                    In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /]. If the rest length is less than 4, the string is padded with '=' characters.



                    ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.



                    ([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$ means the string ends in one of three forms: [A-Za-z0-9+/]{4}, [A-Za-z0-9+/]{3}= or [A-Za-z0-9+/]{2}==.






                    share|improve this answer





















                    • 6





                      Just wanted to verify so please help with my question : What is the guarantee that this regex will always refers to only base64 string?? If there is any string having no space and it is multiple of 4 characters, then will that string be considered as base64 string????

                      – DShah
                      Oct 1 '12 at 10:11








                    • 3





                      Then it is a valid base64 string which can be decoded. You could add a minimum length constraint; for example, instead of zero or more repetitions of groups of four, require (say) four or more. It depends on your problem, too; if your users often enter a single word in a language with long words and pure ASCII (Hawaiian?) it's more error-prone than if non-base64 input typically contains spaces, punctuation, etc.

                      – tripleee
                      Nov 22 '12 at 21:43













                    • @Didier Ghys it seems this base64 encoded string IHRlc3QgbWVzc2FnZQoK does not much the regex. Or maybe it is not base64 encoded ? though base64_decode('IHRlc3QgbWVzc2FnZQoK') outputs write string - test message

                      – dav
                      Dec 24 '12 at 8:32






                    • 51





                      This only tell that an input could have been a b64 encoded value, but it does not tell whether or not the input is actually a b64 encoded value. In other words, abcd will match, but it is not necessarily represent the encoded value of rather just a plain abcd input

                      – Tzury Bar Yochay
                      May 19 '13 at 10:10






                    • 3





                      Your regexp is incorrect, since it does not match the empty string, with is the base64 encoding of zero-length binary data according to RFC 4648.

                      – reddish
                      Feb 19 '17 at 16:53
















                    194














                    You can use the following regular expression to check if a string is base64 encoded or not:



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


                    In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /]. If the rest length is less than 4, the string is padded with '=' characters.



                    ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.



                    ([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$ means the string ends in one of three forms: [A-Za-z0-9+/]{4}, [A-Za-z0-9+/]{3}= or [A-Za-z0-9+/]{2}==.






                    share|improve this answer





















                    • 6





                      Just wanted to verify so please help with my question : What is the guarantee that this regex will always refers to only base64 string?? If there is any string having no space and it is multiple of 4 characters, then will that string be considered as base64 string????

                      – DShah
                      Oct 1 '12 at 10:11








                    • 3





                      Then it is a valid base64 string which can be decoded. You could add a minimum length constraint; for example, instead of zero or more repetitions of groups of four, require (say) four or more. It depends on your problem, too; if your users often enter a single word in a language with long words and pure ASCII (Hawaiian?) it's more error-prone than if non-base64 input typically contains spaces, punctuation, etc.

                      – tripleee
                      Nov 22 '12 at 21:43













                    • @Didier Ghys it seems this base64 encoded string IHRlc3QgbWVzc2FnZQoK does not much the regex. Or maybe it is not base64 encoded ? though base64_decode('IHRlc3QgbWVzc2FnZQoK') outputs write string - test message

                      – dav
                      Dec 24 '12 at 8:32






                    • 51





                      This only tell that an input could have been a b64 encoded value, but it does not tell whether or not the input is actually a b64 encoded value. In other words, abcd will match, but it is not necessarily represent the encoded value of rather just a plain abcd input

                      – Tzury Bar Yochay
                      May 19 '13 at 10:10






                    • 3





                      Your regexp is incorrect, since it does not match the empty string, with is the base64 encoding of zero-length binary data according to RFC 4648.

                      – reddish
                      Feb 19 '17 at 16:53














                    194












                    194








                    194







                    You can use the following regular expression to check if a string is base64 encoded or not:



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


                    In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /]. If the rest length is less than 4, the string is padded with '=' characters.



                    ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.



                    ([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$ means the string ends in one of three forms: [A-Za-z0-9+/]{4}, [A-Za-z0-9+/]{3}= or [A-Za-z0-9+/]{2}==.






                    share|improve this answer















                    You can use the following regular expression to check if a string is base64 encoded or not:



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


                    In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /]. If the rest length is less than 4, the string is padded with '=' characters.



                    ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.



                    ([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$ means the string ends in one of three forms: [A-Za-z0-9+/]{4}, [A-Za-z0-9+/]{3}= or [A-Za-z0-9+/]{2}==.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 22 '18 at 8:47









                    Luis Colorado

                    4,3751718




                    4,3751718










                    answered Dec 20 '11 at 6:39









                    xuanyuanzhiyuanxuanyuanzhiyuan

                    2,3771106




                    2,3771106








                    • 6





                      Just wanted to verify so please help with my question : What is the guarantee that this regex will always refers to only base64 string?? If there is any string having no space and it is multiple of 4 characters, then will that string be considered as base64 string????

                      – DShah
                      Oct 1 '12 at 10:11








                    • 3





                      Then it is a valid base64 string which can be decoded. You could add a minimum length constraint; for example, instead of zero or more repetitions of groups of four, require (say) four or more. It depends on your problem, too; if your users often enter a single word in a language with long words and pure ASCII (Hawaiian?) it's more error-prone than if non-base64 input typically contains spaces, punctuation, etc.

                      – tripleee
                      Nov 22 '12 at 21:43













                    • @Didier Ghys it seems this base64 encoded string IHRlc3QgbWVzc2FnZQoK does not much the regex. Or maybe it is not base64 encoded ? though base64_decode('IHRlc3QgbWVzc2FnZQoK') outputs write string - test message

                      – dav
                      Dec 24 '12 at 8:32






                    • 51





                      This only tell that an input could have been a b64 encoded value, but it does not tell whether or not the input is actually a b64 encoded value. In other words, abcd will match, but it is not necessarily represent the encoded value of rather just a plain abcd input

                      – Tzury Bar Yochay
                      May 19 '13 at 10:10






                    • 3





                      Your regexp is incorrect, since it does not match the empty string, with is the base64 encoding of zero-length binary data according to RFC 4648.

                      – reddish
                      Feb 19 '17 at 16:53














                    • 6





                      Just wanted to verify so please help with my question : What is the guarantee that this regex will always refers to only base64 string?? If there is any string having no space and it is multiple of 4 characters, then will that string be considered as base64 string????

                      – DShah
                      Oct 1 '12 at 10:11








                    • 3





                      Then it is a valid base64 string which can be decoded. You could add a minimum length constraint; for example, instead of zero or more repetitions of groups of four, require (say) four or more. It depends on your problem, too; if your users often enter a single word in a language with long words and pure ASCII (Hawaiian?) it's more error-prone than if non-base64 input typically contains spaces, punctuation, etc.

                      – tripleee
                      Nov 22 '12 at 21:43













                    • @Didier Ghys it seems this base64 encoded string IHRlc3QgbWVzc2FnZQoK does not much the regex. Or maybe it is not base64 encoded ? though base64_decode('IHRlc3QgbWVzc2FnZQoK') outputs write string - test message

                      – dav
                      Dec 24 '12 at 8:32






                    • 51





                      This only tell that an input could have been a b64 encoded value, but it does not tell whether or not the input is actually a b64 encoded value. In other words, abcd will match, but it is not necessarily represent the encoded value of rather just a plain abcd input

                      – Tzury Bar Yochay
                      May 19 '13 at 10:10






                    • 3





                      Your regexp is incorrect, since it does not match the empty string, with is the base64 encoding of zero-length binary data according to RFC 4648.

                      – reddish
                      Feb 19 '17 at 16:53








                    6




                    6





                    Just wanted to verify so please help with my question : What is the guarantee that this regex will always refers to only base64 string?? If there is any string having no space and it is multiple of 4 characters, then will that string be considered as base64 string????

                    – DShah
                    Oct 1 '12 at 10:11







                    Just wanted to verify so please help with my question : What is the guarantee that this regex will always refers to only base64 string?? If there is any string having no space and it is multiple of 4 characters, then will that string be considered as base64 string????

                    – DShah
                    Oct 1 '12 at 10:11






                    3




                    3





                    Then it is a valid base64 string which can be decoded. You could add a minimum length constraint; for example, instead of zero or more repetitions of groups of four, require (say) four or more. It depends on your problem, too; if your users often enter a single word in a language with long words and pure ASCII (Hawaiian?) it's more error-prone than if non-base64 input typically contains spaces, punctuation, etc.

                    – tripleee
                    Nov 22 '12 at 21:43







                    Then it is a valid base64 string which can be decoded. You could add a minimum length constraint; for example, instead of zero or more repetitions of groups of four, require (say) four or more. It depends on your problem, too; if your users often enter a single word in a language with long words and pure ASCII (Hawaiian?) it's more error-prone than if non-base64 input typically contains spaces, punctuation, etc.

                    – tripleee
                    Nov 22 '12 at 21:43















                    @Didier Ghys it seems this base64 encoded string IHRlc3QgbWVzc2FnZQoK does not much the regex. Or maybe it is not base64 encoded ? though base64_decode('IHRlc3QgbWVzc2FnZQoK') outputs write string - test message

                    – dav
                    Dec 24 '12 at 8:32





                    @Didier Ghys it seems this base64 encoded string IHRlc3QgbWVzc2FnZQoK does not much the regex. Or maybe it is not base64 encoded ? though base64_decode('IHRlc3QgbWVzc2FnZQoK') outputs write string - test message

                    – dav
                    Dec 24 '12 at 8:32




                    51




                    51





                    This only tell that an input could have been a b64 encoded value, but it does not tell whether or not the input is actually a b64 encoded value. In other words, abcd will match, but it is not necessarily represent the encoded value of rather just a plain abcd input

                    – Tzury Bar Yochay
                    May 19 '13 at 10:10





                    This only tell that an input could have been a b64 encoded value, but it does not tell whether or not the input is actually a b64 encoded value. In other words, abcd will match, but it is not necessarily represent the encoded value of rather just a plain abcd input

                    – Tzury Bar Yochay
                    May 19 '13 at 10:10




                    3




                    3





                    Your regexp is incorrect, since it does not match the empty string, with is the base64 encoding of zero-length binary data according to RFC 4648.

                    – reddish
                    Feb 19 '17 at 16:53





                    Your regexp is incorrect, since it does not match the empty string, with is the base64 encoding of zero-length binary data according to RFC 4648.

                    – reddish
                    Feb 19 '17 at 16:53













                    42














                    If you are using Java, you can actually use commons-codec library



                    import org.apache.commons.codec.binary.Base64;

                    String stringToBeChecked = "...";
                    boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());





                    share|improve this answer



















                    • 13





                      from the documentation: isArrayByteBase64(byte arrayOctet) Deprecated. 1.5 Use isBase64(byte), will be removed in 2.0.

                      – Avinash R
                      Dec 5 '13 at 4:32








                    • 6





                      You can use also Base64.isBase64(String base64) instead of converting it to byte array yourself.

                      – Sasa
                      Feb 27 '14 at 12:00








                    • 5





                      Sadly, based on documentation: commons.apache.org/proper/commons-codec/apidocs/org/apache/… : "Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid." This means that this methods has some false positives like "whitespace" or numbers ("0", "1").

                      – Christian Vielma
                      Feb 2 '15 at 19:23











                    • for string Base64.isBase64(content)

                      – ema
                      Feb 25 '16 at 17:17






                    • 1





                      This answer is wrong because given stringToBeChecked="some plain text" then it sets boolean isBase64=true even though it's not a Base64 encoded value. Read the source for commons-codec-1.4 Base64.isArrayByteBase64() it only checks that each character in the string is valid to be considered for Base64 encoding and allows white space.

                      – Brad
                      Apr 27 '17 at 11:30


















                    42














                    If you are using Java, you can actually use commons-codec library



                    import org.apache.commons.codec.binary.Base64;

                    String stringToBeChecked = "...";
                    boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());





                    share|improve this answer



















                    • 13





                      from the documentation: isArrayByteBase64(byte arrayOctet) Deprecated. 1.5 Use isBase64(byte), will be removed in 2.0.

                      – Avinash R
                      Dec 5 '13 at 4:32








                    • 6





                      You can use also Base64.isBase64(String base64) instead of converting it to byte array yourself.

                      – Sasa
                      Feb 27 '14 at 12:00








                    • 5





                      Sadly, based on documentation: commons.apache.org/proper/commons-codec/apidocs/org/apache/… : "Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid." This means that this methods has some false positives like "whitespace" or numbers ("0", "1").

                      – Christian Vielma
                      Feb 2 '15 at 19:23











                    • for string Base64.isBase64(content)

                      – ema
                      Feb 25 '16 at 17:17






                    • 1





                      This answer is wrong because given stringToBeChecked="some plain text" then it sets boolean isBase64=true even though it's not a Base64 encoded value. Read the source for commons-codec-1.4 Base64.isArrayByteBase64() it only checks that each character in the string is valid to be considered for Base64 encoding and allows white space.

                      – Brad
                      Apr 27 '17 at 11:30
















                    42












                    42








                    42







                    If you are using Java, you can actually use commons-codec library



                    import org.apache.commons.codec.binary.Base64;

                    String stringToBeChecked = "...";
                    boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());





                    share|improve this answer













                    If you are using Java, you can actually use commons-codec library



                    import org.apache.commons.codec.binary.Base64;

                    String stringToBeChecked = "...";
                    boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 8 '13 at 15:08









                    zihaoyuzihaoyu

                    2,327103546




                    2,327103546








                    • 13





                      from the documentation: isArrayByteBase64(byte arrayOctet) Deprecated. 1.5 Use isBase64(byte), will be removed in 2.0.

                      – Avinash R
                      Dec 5 '13 at 4:32








                    • 6





                      You can use also Base64.isBase64(String base64) instead of converting it to byte array yourself.

                      – Sasa
                      Feb 27 '14 at 12:00








                    • 5





                      Sadly, based on documentation: commons.apache.org/proper/commons-codec/apidocs/org/apache/… : "Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid." This means that this methods has some false positives like "whitespace" or numbers ("0", "1").

                      – Christian Vielma
                      Feb 2 '15 at 19:23











                    • for string Base64.isBase64(content)

                      – ema
                      Feb 25 '16 at 17:17






                    • 1





                      This answer is wrong because given stringToBeChecked="some plain text" then it sets boolean isBase64=true even though it's not a Base64 encoded value. Read the source for commons-codec-1.4 Base64.isArrayByteBase64() it only checks that each character in the string is valid to be considered for Base64 encoding and allows white space.

                      – Brad
                      Apr 27 '17 at 11:30
















                    • 13





                      from the documentation: isArrayByteBase64(byte arrayOctet) Deprecated. 1.5 Use isBase64(byte), will be removed in 2.0.

                      – Avinash R
                      Dec 5 '13 at 4:32








                    • 6





                      You can use also Base64.isBase64(String base64) instead of converting it to byte array yourself.

                      – Sasa
                      Feb 27 '14 at 12:00








                    • 5





                      Sadly, based on documentation: commons.apache.org/proper/commons-codec/apidocs/org/apache/… : "Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid." This means that this methods has some false positives like "whitespace" or numbers ("0", "1").

                      – Christian Vielma
                      Feb 2 '15 at 19:23











                    • for string Base64.isBase64(content)

                      – ema
                      Feb 25 '16 at 17:17






                    • 1





                      This answer is wrong because given stringToBeChecked="some plain text" then it sets boolean isBase64=true even though it's not a Base64 encoded value. Read the source for commons-codec-1.4 Base64.isArrayByteBase64() it only checks that each character in the string is valid to be considered for Base64 encoding and allows white space.

                      – Brad
                      Apr 27 '17 at 11:30










                    13




                    13





                    from the documentation: isArrayByteBase64(byte arrayOctet) Deprecated. 1.5 Use isBase64(byte), will be removed in 2.0.

                    – Avinash R
                    Dec 5 '13 at 4:32







                    from the documentation: isArrayByteBase64(byte arrayOctet) Deprecated. 1.5 Use isBase64(byte), will be removed in 2.0.

                    – Avinash R
                    Dec 5 '13 at 4:32






                    6




                    6





                    You can use also Base64.isBase64(String base64) instead of converting it to byte array yourself.

                    – Sasa
                    Feb 27 '14 at 12:00







                    You can use also Base64.isBase64(String base64) instead of converting it to byte array yourself.

                    – Sasa
                    Feb 27 '14 at 12:00






                    5




                    5





                    Sadly, based on documentation: commons.apache.org/proper/commons-codec/apidocs/org/apache/… : "Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid." This means that this methods has some false positives like "whitespace" or numbers ("0", "1").

                    – Christian Vielma
                    Feb 2 '15 at 19:23





                    Sadly, based on documentation: commons.apache.org/proper/commons-codec/apidocs/org/apache/… : "Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the method treats whitespace as valid." This means that this methods has some false positives like "whitespace" or numbers ("0", "1").

                    – Christian Vielma
                    Feb 2 '15 at 19:23













                    for string Base64.isBase64(content)

                    – ema
                    Feb 25 '16 at 17:17





                    for string Base64.isBase64(content)

                    – ema
                    Feb 25 '16 at 17:17




                    1




                    1





                    This answer is wrong because given stringToBeChecked="some plain text" then it sets boolean isBase64=true even though it's not a Base64 encoded value. Read the source for commons-codec-1.4 Base64.isArrayByteBase64() it only checks that each character in the string is valid to be considered for Base64 encoding and allows white space.

                    – Brad
                    Apr 27 '17 at 11:30







                    This answer is wrong because given stringToBeChecked="some plain text" then it sets boolean isBase64=true even though it's not a Base64 encoded value. Read the source for commons-codec-1.4 Base64.isArrayByteBase64() it only checks that each character in the string is valid to be considered for Base64 encoding and allows white space.

                    – Brad
                    Apr 27 '17 at 11:30













                    39














                    Well you can:




                    • Check that the length is a multiple of 4 characters

                    • Check that every character is in the set A-Z, a-z, 0-9, +, / except for padding at the end which is 0, 1 or 2 '=' characters


                    If you're expecting that it will be base64, then you can probably just use whatever library is available on your platform to try to decode it to a byte array, throwing an exception if it's not valid base 64. That depends on your platform, of course.






                    share|improve this answer




























                      39














                      Well you can:




                      • Check that the length is a multiple of 4 characters

                      • Check that every character is in the set A-Z, a-z, 0-9, +, / except for padding at the end which is 0, 1 or 2 '=' characters


                      If you're expecting that it will be base64, then you can probably just use whatever library is available on your platform to try to decode it to a byte array, throwing an exception if it's not valid base 64. That depends on your platform, of course.






                      share|improve this answer


























                        39












                        39








                        39







                        Well you can:




                        • Check that the length is a multiple of 4 characters

                        • Check that every character is in the set A-Z, a-z, 0-9, +, / except for padding at the end which is 0, 1 or 2 '=' characters


                        If you're expecting that it will be base64, then you can probably just use whatever library is available on your platform to try to decode it to a byte array, throwing an exception if it's not valid base 64. That depends on your platform, of course.






                        share|improve this answer













                        Well you can:




                        • Check that the length is a multiple of 4 characters

                        • Check that every character is in the set A-Z, a-z, 0-9, +, / except for padding at the end which is 0, 1 or 2 '=' characters


                        If you're expecting that it will be base64, then you can probably just use whatever library is available on your platform to try to decode it to a byte array, throwing an exception if it's not valid base 64. That depends on your platform, of course.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Dec 20 '11 at 6:23









                        Jon SkeetJon Skeet

                        1092k69279688456




                        1092k69279688456























                            11














                            Try like this for PHP5



                            //where $json is some data that can be base64 encoded
                            $json=some_data;

                            //this will check whether data is base64 encoded or not
                            if (base64_decode($json, true) == true)
                            {
                            echo "base64 encoded";
                            }
                            else
                            {
                            echo "not base64 encoded";
                            }





                            share|improve this answer


























                            • why -1. Its working fine for me

                              – Suneel Kumar
                              Dec 10 '13 at 8:08






                            • 1





                              Which language is this? The question was asked without referring to a language

                              – Ozkan
                              Nov 27 '14 at 10:53











                            • @Ozkan its in php5

                              – Suneel Kumar
                              Nov 27 '14 at 14:03











                            • this will not work. read the docs Returns FALSE if input contains character from outside the base64 alphabet. base64_decode

                              – Aley
                              Apr 30 '16 at 21:29











                            • How? if input contains outside character then it is not base64, right?

                              – Suneel Kumar
                              Feb 1 '17 at 13:16
















                            11














                            Try like this for PHP5



                            //where $json is some data that can be base64 encoded
                            $json=some_data;

                            //this will check whether data is base64 encoded or not
                            if (base64_decode($json, true) == true)
                            {
                            echo "base64 encoded";
                            }
                            else
                            {
                            echo "not base64 encoded";
                            }





                            share|improve this answer


























                            • why -1. Its working fine for me

                              – Suneel Kumar
                              Dec 10 '13 at 8:08






                            • 1





                              Which language is this? The question was asked without referring to a language

                              – Ozkan
                              Nov 27 '14 at 10:53











                            • @Ozkan its in php5

                              – Suneel Kumar
                              Nov 27 '14 at 14:03











                            • this will not work. read the docs Returns FALSE if input contains character from outside the base64 alphabet. base64_decode

                              – Aley
                              Apr 30 '16 at 21:29











                            • How? if input contains outside character then it is not base64, right?

                              – Suneel Kumar
                              Feb 1 '17 at 13:16














                            11












                            11








                            11







                            Try like this for PHP5



                            //where $json is some data that can be base64 encoded
                            $json=some_data;

                            //this will check whether data is base64 encoded or not
                            if (base64_decode($json, true) == true)
                            {
                            echo "base64 encoded";
                            }
                            else
                            {
                            echo "not base64 encoded";
                            }





                            share|improve this answer















                            Try like this for PHP5



                            //where $json is some data that can be base64 encoded
                            $json=some_data;

                            //this will check whether data is base64 encoded or not
                            if (base64_decode($json, true) == true)
                            {
                            echo "base64 encoded";
                            }
                            else
                            {
                            echo "not base64 encoded";
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Feb 1 '17 at 13:17

























                            answered Nov 22 '13 at 13:12









                            Suneel KumarSuneel Kumar

                            2,92212333




                            2,92212333













                            • why -1. Its working fine for me

                              – Suneel Kumar
                              Dec 10 '13 at 8:08






                            • 1





                              Which language is this? The question was asked without referring to a language

                              – Ozkan
                              Nov 27 '14 at 10:53











                            • @Ozkan its in php5

                              – Suneel Kumar
                              Nov 27 '14 at 14:03











                            • this will not work. read the docs Returns FALSE if input contains character from outside the base64 alphabet. base64_decode

                              – Aley
                              Apr 30 '16 at 21:29











                            • How? if input contains outside character then it is not base64, right?

                              – Suneel Kumar
                              Feb 1 '17 at 13:16



















                            • why -1. Its working fine for me

                              – Suneel Kumar
                              Dec 10 '13 at 8:08






                            • 1





                              Which language is this? The question was asked without referring to a language

                              – Ozkan
                              Nov 27 '14 at 10:53











                            • @Ozkan its in php5

                              – Suneel Kumar
                              Nov 27 '14 at 14:03











                            • this will not work. read the docs Returns FALSE if input contains character from outside the base64 alphabet. base64_decode

                              – Aley
                              Apr 30 '16 at 21:29











                            • How? if input contains outside character then it is not base64, right?

                              – Suneel Kumar
                              Feb 1 '17 at 13:16

















                            why -1. Its working fine for me

                            – Suneel Kumar
                            Dec 10 '13 at 8:08





                            why -1. Its working fine for me

                            – Suneel Kumar
                            Dec 10 '13 at 8:08




                            1




                            1





                            Which language is this? The question was asked without referring to a language

                            – Ozkan
                            Nov 27 '14 at 10:53





                            Which language is this? The question was asked without referring to a language

                            – Ozkan
                            Nov 27 '14 at 10:53













                            @Ozkan its in php5

                            – Suneel Kumar
                            Nov 27 '14 at 14:03





                            @Ozkan its in php5

                            – Suneel Kumar
                            Nov 27 '14 at 14:03













                            this will not work. read the docs Returns FALSE if input contains character from outside the base64 alphabet. base64_decode

                            – Aley
                            Apr 30 '16 at 21:29





                            this will not work. read the docs Returns FALSE if input contains character from outside the base64 alphabet. base64_decode

                            – Aley
                            Apr 30 '16 at 21:29













                            How? if input contains outside character then it is not base64, right?

                            – Suneel Kumar
                            Feb 1 '17 at 13:16





                            How? if input contains outside character then it is not base64, right?

                            – Suneel Kumar
                            Feb 1 '17 at 13:16











                            6














                            As of Java 8, you can simply use java.util.Base64 to try and decode the string:



                            String someString = "...";
                            Base64.Decoder decoder = Base64.getDecoder();

                            try {
                            decoder.decode(someString);
                            } catch(IllegalArgumentException iae) {
                            // That string wasn't valid.
                            }





                            share|improve this answer



















                            • 1





                              yes, it's an option, but don't forget that catch is quite expensive operation in Java

                              – panser
                              Dec 28 '17 at 22:45
















                            6














                            As of Java 8, you can simply use java.util.Base64 to try and decode the string:



                            String someString = "...";
                            Base64.Decoder decoder = Base64.getDecoder();

                            try {
                            decoder.decode(someString);
                            } catch(IllegalArgumentException iae) {
                            // That string wasn't valid.
                            }





                            share|improve this answer



















                            • 1





                              yes, it's an option, but don't forget that catch is quite expensive operation in Java

                              – panser
                              Dec 28 '17 at 22:45














                            6












                            6








                            6







                            As of Java 8, you can simply use java.util.Base64 to try and decode the string:



                            String someString = "...";
                            Base64.Decoder decoder = Base64.getDecoder();

                            try {
                            decoder.decode(someString);
                            } catch(IllegalArgumentException iae) {
                            // That string wasn't valid.
                            }





                            share|improve this answer













                            As of Java 8, you can simply use java.util.Base64 to try and decode the string:



                            String someString = "...";
                            Base64.Decoder decoder = Base64.getDecoder();

                            try {
                            decoder.decode(someString);
                            } catch(IllegalArgumentException iae) {
                            // That string wasn't valid.
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 5 '16 at 21:23









                            PhilippePhilippe

                            7,45422950




                            7,45422950








                            • 1





                              yes, it's an option, but don't forget that catch is quite expensive operation in Java

                              – panser
                              Dec 28 '17 at 22:45














                            • 1





                              yes, it's an option, but don't forget that catch is quite expensive operation in Java

                              – panser
                              Dec 28 '17 at 22:45








                            1




                            1





                            yes, it's an option, but don't forget that catch is quite expensive operation in Java

                            – panser
                            Dec 28 '17 at 22:45





                            yes, it's an option, but don't forget that catch is quite expensive operation in Java

                            – panser
                            Dec 28 '17 at 22:45











                            4














                            There are many variants of Base64, so consider just determining if your string resembles the varient you expect to handle. As such, you may need to adjust the regex below with respect to the index and padding characters (i.e. +, /, =).



                            class String
                            def resembles_base64?
                            self.length % 4 == 0 && self =~ /^[A-Za-z0-9+/=]+Z/
                            end
                            end


                            Usage:



                            raise 'the string does not resemble Base64' unless my_string.resembles_base64?





                            share|improve this answer




























                              4














                              There are many variants of Base64, so consider just determining if your string resembles the varient you expect to handle. As such, you may need to adjust the regex below with respect to the index and padding characters (i.e. +, /, =).



                              class String
                              def resembles_base64?
                              self.length % 4 == 0 && self =~ /^[A-Za-z0-9+/=]+Z/
                              end
                              end


                              Usage:



                              raise 'the string does not resemble Base64' unless my_string.resembles_base64?





                              share|improve this answer


























                                4












                                4








                                4







                                There are many variants of Base64, so consider just determining if your string resembles the varient you expect to handle. As such, you may need to adjust the regex below with respect to the index and padding characters (i.e. +, /, =).



                                class String
                                def resembles_base64?
                                self.length % 4 == 0 && self =~ /^[A-Za-z0-9+/=]+Z/
                                end
                                end


                                Usage:



                                raise 'the string does not resemble Base64' unless my_string.resembles_base64?





                                share|improve this answer













                                There are many variants of Base64, so consider just determining if your string resembles the varient you expect to handle. As such, you may need to adjust the regex below with respect to the index and padding characters (i.e. +, /, =).



                                class String
                                def resembles_base64?
                                self.length % 4 == 0 && self =~ /^[A-Za-z0-9+/=]+Z/
                                end
                                end


                                Usage:



                                raise 'the string does not resemble Base64' unless my_string.resembles_base64?






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Nov 22 '12 at 21:23









                                user664833user664833

                                10.9k1767113




                                10.9k1767113























                                    4














                                    Check to see IF the string's length is a multiple of 4. Aftwerwards use this regex to make sure all characters in the string are base64 characters.



                                    A[a-zA-Zd/+]+={,2}z



                                    If the library you use adds a newline as a way of observing the 76 max chars per line rule, replace them with empty strings.






                                    share|improve this answer


























                                    • The link mentioned shows 404. Please check and update.

                                      – Ankur
                                      Jul 9 '14 at 10:16











                                    • Sorry @AnkurKumar but that's what happen when people have uncool URLs: they change all the time. I have no idea where it's moved to. I hope you find other useful resources through Google

                                      – Yaw Boakye
                                      Jul 13 '14 at 2:41











                                    • You can always get old pages from web.archive.org - here's the original url. web.archive.org/web/20120919035911/http://… or I posted the text here: gist.github.com/mika76/d09e2b65159e435e7a4cc5b0299c3e84

                                      – Mladen Mihajlovic
                                      Jun 16 '18 at 11:52
















                                    4














                                    Check to see IF the string's length is a multiple of 4. Aftwerwards use this regex to make sure all characters in the string are base64 characters.



                                    A[a-zA-Zd/+]+={,2}z



                                    If the library you use adds a newline as a way of observing the 76 max chars per line rule, replace them with empty strings.






                                    share|improve this answer


























                                    • The link mentioned shows 404. Please check and update.

                                      – Ankur
                                      Jul 9 '14 at 10:16











                                    • Sorry @AnkurKumar but that's what happen when people have uncool URLs: they change all the time. I have no idea where it's moved to. I hope you find other useful resources through Google

                                      – Yaw Boakye
                                      Jul 13 '14 at 2:41











                                    • You can always get old pages from web.archive.org - here's the original url. web.archive.org/web/20120919035911/http://… or I posted the text here: gist.github.com/mika76/d09e2b65159e435e7a4cc5b0299c3e84

                                      – Mladen Mihajlovic
                                      Jun 16 '18 at 11:52














                                    4












                                    4








                                    4







                                    Check to see IF the string's length is a multiple of 4. Aftwerwards use this regex to make sure all characters in the string are base64 characters.



                                    A[a-zA-Zd/+]+={,2}z



                                    If the library you use adds a newline as a way of observing the 76 max chars per line rule, replace them with empty strings.






                                    share|improve this answer















                                    Check to see IF the string's length is a multiple of 4. Aftwerwards use this regex to make sure all characters in the string are base64 characters.



                                    A[a-zA-Zd/+]+={,2}z



                                    If the library you use adds a newline as a way of observing the 76 max chars per line rule, replace them with empty strings.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Jul 13 '14 at 2:41

























                                    answered Mar 9 '13 at 16:36









                                    Yaw BoakyeYaw Boakye

                                    8,23411224




                                    8,23411224













                                    • The link mentioned shows 404. Please check and update.

                                      – Ankur
                                      Jul 9 '14 at 10:16











                                    • Sorry @AnkurKumar but that's what happen when people have uncool URLs: they change all the time. I have no idea where it's moved to. I hope you find other useful resources through Google

                                      – Yaw Boakye
                                      Jul 13 '14 at 2:41











                                    • You can always get old pages from web.archive.org - here's the original url. web.archive.org/web/20120919035911/http://… or I posted the text here: gist.github.com/mika76/d09e2b65159e435e7a4cc5b0299c3e84

                                      – Mladen Mihajlovic
                                      Jun 16 '18 at 11:52



















                                    • The link mentioned shows 404. Please check and update.

                                      – Ankur
                                      Jul 9 '14 at 10:16











                                    • Sorry @AnkurKumar but that's what happen when people have uncool URLs: they change all the time. I have no idea where it's moved to. I hope you find other useful resources through Google

                                      – Yaw Boakye
                                      Jul 13 '14 at 2:41











                                    • You can always get old pages from web.archive.org - here's the original url. web.archive.org/web/20120919035911/http://… or I posted the text here: gist.github.com/mika76/d09e2b65159e435e7a4cc5b0299c3e84

                                      – Mladen Mihajlovic
                                      Jun 16 '18 at 11:52

















                                    The link mentioned shows 404. Please check and update.

                                    – Ankur
                                    Jul 9 '14 at 10:16





                                    The link mentioned shows 404. Please check and update.

                                    – Ankur
                                    Jul 9 '14 at 10:16













                                    Sorry @AnkurKumar but that's what happen when people have uncool URLs: they change all the time. I have no idea where it's moved to. I hope you find other useful resources through Google

                                    – Yaw Boakye
                                    Jul 13 '14 at 2:41





                                    Sorry @AnkurKumar but that's what happen when people have uncool URLs: they change all the time. I have no idea where it's moved to. I hope you find other useful resources through Google

                                    – Yaw Boakye
                                    Jul 13 '14 at 2:41













                                    You can always get old pages from web.archive.org - here's the original url. web.archive.org/web/20120919035911/http://… or I posted the text here: gist.github.com/mika76/d09e2b65159e435e7a4cc5b0299c3e84

                                    – Mladen Mihajlovic
                                    Jun 16 '18 at 11:52





                                    You can always get old pages from web.archive.org - here's the original url. web.archive.org/web/20120919035911/http://… or I posted the text here: gist.github.com/mika76/d09e2b65159e435e7a4cc5b0299c3e84

                                    – Mladen Mihajlovic
                                    Jun 16 '18 at 11:52











                                    4














                                    var base64Rejex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=|[A-Z0-9+/]{4})$/i;
                                    var isBase64Valid = base64Rejex.test(base64Data); // base64Data is the base64 string

                                    if (isBase64Valid) {
                                    // true if base64 formate
                                    console.log('It is base64');
                                    } else {
                                    // false if not in base64 formate
                                    console.log('it is not in base64');
                                    }





                                    share|improve this answer






























                                      4














                                      var base64Rejex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=|[A-Z0-9+/]{4})$/i;
                                      var isBase64Valid = base64Rejex.test(base64Data); // base64Data is the base64 string

                                      if (isBase64Valid) {
                                      // true if base64 formate
                                      console.log('It is base64');
                                      } else {
                                      // false if not in base64 formate
                                      console.log('it is not in base64');
                                      }





                                      share|improve this answer




























                                        4












                                        4








                                        4







                                        var base64Rejex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=|[A-Z0-9+/]{4})$/i;
                                        var isBase64Valid = base64Rejex.test(base64Data); // base64Data is the base64 string

                                        if (isBase64Valid) {
                                        // true if base64 formate
                                        console.log('It is base64');
                                        } else {
                                        // false if not in base64 formate
                                        console.log('it is not in base64');
                                        }





                                        share|improve this answer















                                        var base64Rejex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=|[A-Z0-9+/]{4})$/i;
                                        var isBase64Valid = base64Rejex.test(base64Data); // base64Data is the base64 string

                                        if (isBase64Valid) {
                                        // true if base64 formate
                                        console.log('It is base64');
                                        } else {
                                        // false if not in base64 formate
                                        console.log('it is not in base64');
                                        }






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jul 27 '15 at 14:11









                                        Alex K

                                        6,91683252




                                        6,91683252










                                        answered Jul 6 '15 at 12:28









                                        Deepak SisodiyaDeepak Sisodiya

                                        56759




                                        56759























                                            1














                                            Try this:



                                            public void checkForEncode(String string) {
                                            String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                                            Pattern r = Pattern.compile(pattern);
                                            Matcher m = r.matcher(string);
                                            if (m.find()) {
                                            System.out.println("true");
                                            } else {
                                            System.out.println("false");
                                            }
                                            }





                                            share|improve this answer


























                                            • consider providing an explanation to your code

                                              – arghtype
                                              Oct 28 '15 at 17:38
















                                            1














                                            Try this:



                                            public void checkForEncode(String string) {
                                            String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                                            Pattern r = Pattern.compile(pattern);
                                            Matcher m = r.matcher(string);
                                            if (m.find()) {
                                            System.out.println("true");
                                            } else {
                                            System.out.println("false");
                                            }
                                            }





                                            share|improve this answer


























                                            • consider providing an explanation to your code

                                              – arghtype
                                              Oct 28 '15 at 17:38














                                            1












                                            1








                                            1







                                            Try this:



                                            public void checkForEncode(String string) {
                                            String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                                            Pattern r = Pattern.compile(pattern);
                                            Matcher m = r.matcher(string);
                                            if (m.find()) {
                                            System.out.println("true");
                                            } else {
                                            System.out.println("false");
                                            }
                                            }





                                            share|improve this answer















                                            Try this:



                                            public void checkForEncode(String string) {
                                            String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                                            Pattern r = Pattern.compile(pattern);
                                            Matcher m = r.matcher(string);
                                            if (m.find()) {
                                            System.out.println("true");
                                            } else {
                                            System.out.println("false");
                                            }
                                            }






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Oct 28 '15 at 18:28









                                            arghtype

                                            3,143113248




                                            3,143113248










                                            answered Oct 28 '15 at 17:17









                                            user5499458user5499458

                                            111




                                            111













                                            • consider providing an explanation to your code

                                              – arghtype
                                              Oct 28 '15 at 17:38



















                                            • consider providing an explanation to your code

                                              – arghtype
                                              Oct 28 '15 at 17:38

















                                            consider providing an explanation to your code

                                            – arghtype
                                            Oct 28 '15 at 17:38





                                            consider providing an explanation to your code

                                            – arghtype
                                            Oct 28 '15 at 17:38











                                            1














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


                                            this regular expression helped me identify the base64 in my application in rails, I only had one problem, it is that it recognizes the string "errorDescripcion", I generate an error, to solve it just validate the length of a string.






                                            share|improve this answer


























                                            • The above regex /^.....$/.match(my_string) gives formatting error by saying 'Unmatched closing )'

                                              – james2611nov
                                              May 17 '18 at 14:57











                                            • And with 'premature end of char-class: /^(([A-Za-z0-9+/' syntax errors.

                                              – james2611nov
                                              May 17 '18 at 15:22











                                            • Nevermind fixed it by adding in front of every / character.

                                              – james2611nov
                                              May 17 '18 at 15:28











                                            • errorDescription is a valid base64 string, it decodes into the binary sequence of bytes (in hex): 7a ba e8 ac 37 ac 72 b8 a9 b6 2a 27.

                                              – Luis Colorado
                                              Nov 22 '18 at 9:03
















                                            1














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


                                            this regular expression helped me identify the base64 in my application in rails, I only had one problem, it is that it recognizes the string "errorDescripcion", I generate an error, to solve it just validate the length of a string.






                                            share|improve this answer


























                                            • The above regex /^.....$/.match(my_string) gives formatting error by saying 'Unmatched closing )'

                                              – james2611nov
                                              May 17 '18 at 14:57











                                            • And with 'premature end of char-class: /^(([A-Za-z0-9+/' syntax errors.

                                              – james2611nov
                                              May 17 '18 at 15:22











                                            • Nevermind fixed it by adding in front of every / character.

                                              – james2611nov
                                              May 17 '18 at 15:28











                                            • errorDescription is a valid base64 string, it decodes into the binary sequence of bytes (in hex): 7a ba e8 ac 37 ac 72 b8 a9 b6 2a 27.

                                              – Luis Colorado
                                              Nov 22 '18 at 9:03














                                            1












                                            1








                                            1







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


                                            this regular expression helped me identify the base64 in my application in rails, I only had one problem, it is that it recognizes the string "errorDescripcion", I generate an error, to solve it just validate the length of a string.






                                            share|improve this answer















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


                                            this regular expression helped me identify the base64 in my application in rails, I only had one problem, it is that it recognizes the string "errorDescripcion", I generate an error, to solve it just validate the length of a string.







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Jan 7 at 22:34









                                            mayo

                                            2,4332036




                                            2,4332036










                                            answered Mar 7 '18 at 13:45









                                            OnironautaOnironauta

                                            111




                                            111













                                            • The above regex /^.....$/.match(my_string) gives formatting error by saying 'Unmatched closing )'

                                              – james2611nov
                                              May 17 '18 at 14:57











                                            • And with 'premature end of char-class: /^(([A-Za-z0-9+/' syntax errors.

                                              – james2611nov
                                              May 17 '18 at 15:22











                                            • Nevermind fixed it by adding in front of every / character.

                                              – james2611nov
                                              May 17 '18 at 15:28











                                            • errorDescription is a valid base64 string, it decodes into the binary sequence of bytes (in hex): 7a ba e8 ac 37 ac 72 b8 a9 b6 2a 27.

                                              – Luis Colorado
                                              Nov 22 '18 at 9:03



















                                            • The above regex /^.....$/.match(my_string) gives formatting error by saying 'Unmatched closing )'

                                              – james2611nov
                                              May 17 '18 at 14:57











                                            • And with 'premature end of char-class: /^(([A-Za-z0-9+/' syntax errors.

                                              – james2611nov
                                              May 17 '18 at 15:22











                                            • Nevermind fixed it by adding in front of every / character.

                                              – james2611nov
                                              May 17 '18 at 15:28











                                            • errorDescription is a valid base64 string, it decodes into the binary sequence of bytes (in hex): 7a ba e8 ac 37 ac 72 b8 a9 b6 2a 27.

                                              – Luis Colorado
                                              Nov 22 '18 at 9:03

















                                            The above regex /^.....$/.match(my_string) gives formatting error by saying 'Unmatched closing )'

                                            – james2611nov
                                            May 17 '18 at 14:57





                                            The above regex /^.....$/.match(my_string) gives formatting error by saying 'Unmatched closing )'

                                            – james2611nov
                                            May 17 '18 at 14:57













                                            And with 'premature end of char-class: /^(([A-Za-z0-9+/' syntax errors.

                                            – james2611nov
                                            May 17 '18 at 15:22





                                            And with 'premature end of char-class: /^(([A-Za-z0-9+/' syntax errors.

                                            – james2611nov
                                            May 17 '18 at 15:22













                                            Nevermind fixed it by adding in front of every / character.

                                            – james2611nov
                                            May 17 '18 at 15:28





                                            Nevermind fixed it by adding in front of every / character.

                                            – james2611nov
                                            May 17 '18 at 15:28













                                            errorDescription is a valid base64 string, it decodes into the binary sequence of bytes (in hex): 7a ba e8 ac 37 ac 72 b8 a9 b6 2a 27.

                                            – Luis Colorado
                                            Nov 22 '18 at 9:03





                                            errorDescription is a valid base64 string, it decodes into the binary sequence of bytes (in hex): 7a ba e8 ac 37 ac 72 b8 a9 b6 2a 27.

                                            – Luis Colorado
                                            Nov 22 '18 at 9:03











                                            1














                                            C#
                                            This is performing great:



                                            static readonly Regex _base64RegexPattern = new Regex(BASE64_REGEX_STRING, RegexOptions.Compiled);

                                            private const String BASE64_REGEX_STRING = @"^[a-zA-Z0-9+/]*={0,3}$";

                                            private static bool IsBase64(this String base64String)
                                            {
                                            var rs = (!string.IsNullOrEmpty(base64String) && !string.IsNullOrWhiteSpace(base64String) && base64String.Length != 0 && base64String.Length % 4 == 0 && !base64String.Contains(" ") && !base64String.Contains("t") && !base64String.Contains("r") && !base64String.Contains("n")) && (base64String.Length % 4 == 0 && _base64RegexPattern.Match(base64String, 0).Success);
                                            return rs;
                                            }





                                            share|improve this answer


























                                            • Console.WriteLine("test".IsBase64()); // true

                                              – Langdon
                                              Sep 7 '18 at 20:32













                                            • Recommend to switch programming language to solve a problem is in general not a valid response.

                                              – Luis Colorado
                                              Nov 22 '18 at 9:04
















                                            1














                                            C#
                                            This is performing great:



                                            static readonly Regex _base64RegexPattern = new Regex(BASE64_REGEX_STRING, RegexOptions.Compiled);

                                            private const String BASE64_REGEX_STRING = @"^[a-zA-Z0-9+/]*={0,3}$";

                                            private static bool IsBase64(this String base64String)
                                            {
                                            var rs = (!string.IsNullOrEmpty(base64String) && !string.IsNullOrWhiteSpace(base64String) && base64String.Length != 0 && base64String.Length % 4 == 0 && !base64String.Contains(" ") && !base64String.Contains("t") && !base64String.Contains("r") && !base64String.Contains("n")) && (base64String.Length % 4 == 0 && _base64RegexPattern.Match(base64String, 0).Success);
                                            return rs;
                                            }





                                            share|improve this answer


























                                            • Console.WriteLine("test".IsBase64()); // true

                                              – Langdon
                                              Sep 7 '18 at 20:32













                                            • Recommend to switch programming language to solve a problem is in general not a valid response.

                                              – Luis Colorado
                                              Nov 22 '18 at 9:04














                                            1












                                            1








                                            1







                                            C#
                                            This is performing great:



                                            static readonly Regex _base64RegexPattern = new Regex(BASE64_REGEX_STRING, RegexOptions.Compiled);

                                            private const String BASE64_REGEX_STRING = @"^[a-zA-Z0-9+/]*={0,3}$";

                                            private static bool IsBase64(this String base64String)
                                            {
                                            var rs = (!string.IsNullOrEmpty(base64String) && !string.IsNullOrWhiteSpace(base64String) && base64String.Length != 0 && base64String.Length % 4 == 0 && !base64String.Contains(" ") && !base64String.Contains("t") && !base64String.Contains("r") && !base64String.Contains("n")) && (base64String.Length % 4 == 0 && _base64RegexPattern.Match(base64String, 0).Success);
                                            return rs;
                                            }





                                            share|improve this answer















                                            C#
                                            This is performing great:



                                            static readonly Regex _base64RegexPattern = new Regex(BASE64_REGEX_STRING, RegexOptions.Compiled);

                                            private const String BASE64_REGEX_STRING = @"^[a-zA-Z0-9+/]*={0,3}$";

                                            private static bool IsBase64(this String base64String)
                                            {
                                            var rs = (!string.IsNullOrEmpty(base64String) && !string.IsNullOrWhiteSpace(base64String) && base64String.Length != 0 && base64String.Length % 4 == 0 && !base64String.Contains(" ") && !base64String.Contains("t") && !base64String.Contains("r") && !base64String.Contains("n")) && (base64String.Length % 4 == 0 && _base64RegexPattern.Match(base64String, 0).Success);
                                            return rs;
                                            }






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Jan 7 at 22:35









                                            mayo

                                            2,4332036




                                            2,4332036










                                            answered Apr 29 '16 at 11:15









                                            Veni SoutoVeni Souto

                                            243




                                            243













                                            • Console.WriteLine("test".IsBase64()); // true

                                              – Langdon
                                              Sep 7 '18 at 20:32













                                            • Recommend to switch programming language to solve a problem is in general not a valid response.

                                              – Luis Colorado
                                              Nov 22 '18 at 9:04



















                                            • Console.WriteLine("test".IsBase64()); // true

                                              – Langdon
                                              Sep 7 '18 at 20:32













                                            • Recommend to switch programming language to solve a problem is in general not a valid response.

                                              – Luis Colorado
                                              Nov 22 '18 at 9:04

















                                            Console.WriteLine("test".IsBase64()); // true

                                            – Langdon
                                            Sep 7 '18 at 20:32







                                            Console.WriteLine("test".IsBase64()); // true

                                            – Langdon
                                            Sep 7 '18 at 20:32















                                            Recommend to switch programming language to solve a problem is in general not a valid response.

                                            – Luis Colorado
                                            Nov 22 '18 at 9:04





                                            Recommend to switch programming language to solve a problem is in general not a valid response.

                                            – Luis Colorado
                                            Nov 22 '18 at 9:04











                                            0














                                            There is no way to distinct string and base64 encoded, except the string in your system has some specific limitation or identification.






                                            share|improve this answer




























                                              0














                                              There is no way to distinct string and base64 encoded, except the string in your system has some specific limitation or identification.






                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                There is no way to distinct string and base64 encoded, except the string in your system has some specific limitation or identification.






                                                share|improve this answer













                                                There is no way to distinct string and base64 encoded, except the string in your system has some specific limitation or identification.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Dec 20 '11 at 6:23









                                                pinxuepinxue

                                                1,6041016




                                                1,6041016























                                                    0














                                                    This snippet may be useful when you know the length of the original content (e.g. a checksum). It checks that encoded form has the correct length.



                                                    public static boolean isValidBase64( final int initialLength, final String string ) {
                                                    final int padding ;
                                                    final String regexEnd ;
                                                    switch( ( initialLength ) % 3 ) {
                                                    case 1 :
                                                    padding = 2 ;
                                                    regexEnd = "==" ;
                                                    break ;
                                                    case 2 :
                                                    padding = 1 ;
                                                    regexEnd = "=" ;
                                                    break ;
                                                    default :
                                                    padding = 0 ;
                                                    regexEnd = "" ;
                                                    }
                                                    final int encodedLength = ( ( ( initialLength / 3 ) + ( padding > 0 ? 1 : 0 ) ) * 4 ) ;
                                                    final String regex = "[a-zA-Z0-9/\+]{" + ( encodedLength - padding ) + "}" + regexEnd ;
                                                    return Pattern.compile( regex ).matcher( string ).matches() ;
                                                    }





                                                    share|improve this answer




























                                                      0














                                                      This snippet may be useful when you know the length of the original content (e.g. a checksum). It checks that encoded form has the correct length.



                                                      public static boolean isValidBase64( final int initialLength, final String string ) {
                                                      final int padding ;
                                                      final String regexEnd ;
                                                      switch( ( initialLength ) % 3 ) {
                                                      case 1 :
                                                      padding = 2 ;
                                                      regexEnd = "==" ;
                                                      break ;
                                                      case 2 :
                                                      padding = 1 ;
                                                      regexEnd = "=" ;
                                                      break ;
                                                      default :
                                                      padding = 0 ;
                                                      regexEnd = "" ;
                                                      }
                                                      final int encodedLength = ( ( ( initialLength / 3 ) + ( padding > 0 ? 1 : 0 ) ) * 4 ) ;
                                                      final String regex = "[a-zA-Z0-9/\+]{" + ( encodedLength - padding ) + "}" + regexEnd ;
                                                      return Pattern.compile( regex ).matcher( string ).matches() ;
                                                      }





                                                      share|improve this answer


























                                                        0












                                                        0








                                                        0







                                                        This snippet may be useful when you know the length of the original content (e.g. a checksum). It checks that encoded form has the correct length.



                                                        public static boolean isValidBase64( final int initialLength, final String string ) {
                                                        final int padding ;
                                                        final String regexEnd ;
                                                        switch( ( initialLength ) % 3 ) {
                                                        case 1 :
                                                        padding = 2 ;
                                                        regexEnd = "==" ;
                                                        break ;
                                                        case 2 :
                                                        padding = 1 ;
                                                        regexEnd = "=" ;
                                                        break ;
                                                        default :
                                                        padding = 0 ;
                                                        regexEnd = "" ;
                                                        }
                                                        final int encodedLength = ( ( ( initialLength / 3 ) + ( padding > 0 ? 1 : 0 ) ) * 4 ) ;
                                                        final String regex = "[a-zA-Z0-9/\+]{" + ( encodedLength - padding ) + "}" + regexEnd ;
                                                        return Pattern.compile( regex ).matcher( string ).matches() ;
                                                        }





                                                        share|improve this answer













                                                        This snippet may be useful when you know the length of the original content (e.g. a checksum). It checks that encoded form has the correct length.



                                                        public static boolean isValidBase64( final int initialLength, final String string ) {
                                                        final int padding ;
                                                        final String regexEnd ;
                                                        switch( ( initialLength ) % 3 ) {
                                                        case 1 :
                                                        padding = 2 ;
                                                        regexEnd = "==" ;
                                                        break ;
                                                        case 2 :
                                                        padding = 1 ;
                                                        regexEnd = "=" ;
                                                        break ;
                                                        default :
                                                        padding = 0 ;
                                                        regexEnd = "" ;
                                                        }
                                                        final int encodedLength = ( ( ( initialLength / 3 ) + ( padding > 0 ? 1 : 0 ) ) * 4 ) ;
                                                        final String regex = "[a-zA-Z0-9/\+]{" + ( encodedLength - padding ) + "}" + regexEnd ;
                                                        return Pattern.compile( regex ).matcher( string ).matches() ;
                                                        }






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Jul 24 '14 at 19:12









                                                        Laurent CailletteLaurent Caillette

                                                        616917




                                                        616917























                                                            0














                                                            If the RegEx does not work and you know the format style of the original string, you can reverse the logic, by regexing for this format.



                                                            For example I work with base64 encoded xml files and just check if the file contains valid xml markup. If it does not I can assume, that it's base64 decoded. This is not very dynamic but works fine for my small application.






                                                            share|improve this answer




























                                                              0














                                                              If the RegEx does not work and you know the format style of the original string, you can reverse the logic, by regexing for this format.



                                                              For example I work with base64 encoded xml files and just check if the file contains valid xml markup. If it does not I can assume, that it's base64 decoded. This is not very dynamic but works fine for my small application.






                                                              share|improve this answer


























                                                                0












                                                                0








                                                                0







                                                                If the RegEx does not work and you know the format style of the original string, you can reverse the logic, by regexing for this format.



                                                                For example I work with base64 encoded xml files and just check if the file contains valid xml markup. If it does not I can assume, that it's base64 decoded. This is not very dynamic but works fine for my small application.






                                                                share|improve this answer













                                                                If the RegEx does not work and you know the format style of the original string, you can reverse the logic, by regexing for this format.



                                                                For example I work with base64 encoded xml files and just check if the file contains valid xml markup. If it does not I can assume, that it's base64 decoded. This is not very dynamic but works fine for my small application.







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Nov 5 '14 at 11:16









                                                                JankapunktJankapunkt

                                                                3,98831735




                                                                3,98831735























                                                                    0














                                                                    This works in Python:



                                                                    def is_base64(string):
                                                                    if len(string) % 4 == 0 and re.test('^[A-Za-z0-9+/=]+Z', string):
                                                                    return(True)
                                                                    else:
                                                                    return(False)





                                                                    share|improve this answer




























                                                                      0














                                                                      This works in Python:



                                                                      def is_base64(string):
                                                                      if len(string) % 4 == 0 and re.test('^[A-Za-z0-9+/=]+Z', string):
                                                                      return(True)
                                                                      else:
                                                                      return(False)





                                                                      share|improve this answer


























                                                                        0












                                                                        0








                                                                        0







                                                                        This works in Python:



                                                                        def is_base64(string):
                                                                        if len(string) % 4 == 0 and re.test('^[A-Za-z0-9+/=]+Z', string):
                                                                        return(True)
                                                                        else:
                                                                        return(False)





                                                                        share|improve this answer













                                                                        This works in Python:



                                                                        def is_base64(string):
                                                                        if len(string) % 4 == 0 and re.test('^[A-Za-z0-9+/=]+Z', string):
                                                                        return(True)
                                                                        else:
                                                                        return(False)






                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Jan 5 '16 at 16:34









                                                                        bcarrollbcarroll

                                                                        786710




                                                                        786710























                                                                            0














                                                                            This works in Python:



                                                                            import base64

                                                                            def IsBase64(str):
                                                                            try:
                                                                            base64.b64decode(str)
                                                                            return True
                                                                            except Exception as e:
                                                                            return False

                                                                            if IsBase64("ABC"):
                                                                            print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
                                                                            else:
                                                                            print("ABC is NOT Base64-encoded.")

                                                                            if IsBase64("QUJD"):
                                                                            print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
                                                                            else:
                                                                            print("QUJD is NOT Base64-encoded.")


                                                                            Summary: IsBase64("string here") returns true if string here is Base64-encoded, and it returns false if string here was NOT Base64-encoded.






                                                                            share|improve this answer




























                                                                              0














                                                                              This works in Python:



                                                                              import base64

                                                                              def IsBase64(str):
                                                                              try:
                                                                              base64.b64decode(str)
                                                                              return True
                                                                              except Exception as e:
                                                                              return False

                                                                              if IsBase64("ABC"):
                                                                              print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
                                                                              else:
                                                                              print("ABC is NOT Base64-encoded.")

                                                                              if IsBase64("QUJD"):
                                                                              print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
                                                                              else:
                                                                              print("QUJD is NOT Base64-encoded.")


                                                                              Summary: IsBase64("string here") returns true if string here is Base64-encoded, and it returns false if string here was NOT Base64-encoded.






                                                                              share|improve this answer


























                                                                                0












                                                                                0








                                                                                0







                                                                                This works in Python:



                                                                                import base64

                                                                                def IsBase64(str):
                                                                                try:
                                                                                base64.b64decode(str)
                                                                                return True
                                                                                except Exception as e:
                                                                                return False

                                                                                if IsBase64("ABC"):
                                                                                print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
                                                                                else:
                                                                                print("ABC is NOT Base64-encoded.")

                                                                                if IsBase64("QUJD"):
                                                                                print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
                                                                                else:
                                                                                print("QUJD is NOT Base64-encoded.")


                                                                                Summary: IsBase64("string here") returns true if string here is Base64-encoded, and it returns false if string here was NOT Base64-encoded.






                                                                                share|improve this answer













                                                                                This works in Python:



                                                                                import base64

                                                                                def IsBase64(str):
                                                                                try:
                                                                                base64.b64decode(str)
                                                                                return True
                                                                                except Exception as e:
                                                                                return False

                                                                                if IsBase64("ABC"):
                                                                                print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
                                                                                else:
                                                                                print("ABC is NOT Base64-encoded.")

                                                                                if IsBase64("QUJD"):
                                                                                print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
                                                                                else:
                                                                                print("QUJD is NOT Base64-encoded.")


                                                                                Summary: IsBase64("string here") returns true if string here is Base64-encoded, and it returns false if string here was NOT Base64-encoded.







                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Nov 4 '18 at 15:09









                                                                                gavegave

                                                                                848




                                                                                848























                                                                                    0














                                                                                    It is impossible to check if a string is base64 encoded or not. It is only possible to validate if that string is of a base64 encoded string format, which would mean that it could be a string produced by base64 encoding (to check that, string could be validated against a regexp or a library could be used, many other answers to this question provide good ways to check this, so I won't go into details).



                                                                                    For example, string flow is a valid base64 encoded string. But it is impossible to know if it is just a simple string, an English word flow, or is it base 64 encoded string ~Z0






                                                                                    share|improve this answer




























                                                                                      0














                                                                                      It is impossible to check if a string is base64 encoded or not. It is only possible to validate if that string is of a base64 encoded string format, which would mean that it could be a string produced by base64 encoding (to check that, string could be validated against a regexp or a library could be used, many other answers to this question provide good ways to check this, so I won't go into details).



                                                                                      For example, string flow is a valid base64 encoded string. But it is impossible to know if it is just a simple string, an English word flow, or is it base 64 encoded string ~Z0






                                                                                      share|improve this answer


























                                                                                        0












                                                                                        0








                                                                                        0







                                                                                        It is impossible to check if a string is base64 encoded or not. It is only possible to validate if that string is of a base64 encoded string format, which would mean that it could be a string produced by base64 encoding (to check that, string could be validated against a regexp or a library could be used, many other answers to this question provide good ways to check this, so I won't go into details).



                                                                                        For example, string flow is a valid base64 encoded string. But it is impossible to know if it is just a simple string, an English word flow, or is it base 64 encoded string ~Z0






                                                                                        share|improve this answer













                                                                                        It is impossible to check if a string is base64 encoded or not. It is only possible to validate if that string is of a base64 encoded string format, which would mean that it could be a string produced by base64 encoding (to check that, string could be validated against a regexp or a library could be used, many other answers to this question provide good ways to check this, so I won't go into details).



                                                                                        For example, string flow is a valid base64 encoded string. But it is impossible to know if it is just a simple string, an English word flow, or is it base 64 encoded string ~Z0







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Nov 25 '18 at 12:28









                                                                                        AdomasAdomas

                                                                                        247417




                                                                                        247417























                                                                                            -1














                                                                                            Try this using a previously mentioned regex:



                                                                                            String regex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                                                                                            if("TXkgdGVzdCBzdHJpbmc/".matches(regex)){
                                                                                            System.out.println("it's a Base64");
                                                                                            }


                                                                                            ...We can also make a simple validation like, if it has spaces it cannot be Base64:



                                                                                            String myString = "Hello World";
                                                                                            if(myString.contains(" ")){
                                                                                            System.out.println("Not B64");
                                                                                            }else{
                                                                                            System.out.println("Could be B64 encoded, since it has no spaces");
                                                                                            }





                                                                                            share|improve this answer


























                                                                                            • Ok, could you please give a solution then?

                                                                                              – Marco
                                                                                              Jan 17 at 16:08











                                                                                            • working on it :)

                                                                                              – HIRA THAKUR
                                                                                              Jan 18 at 6:45
















                                                                                            -1














                                                                                            Try this using a previously mentioned regex:



                                                                                            String regex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                                                                                            if("TXkgdGVzdCBzdHJpbmc/".matches(regex)){
                                                                                            System.out.println("it's a Base64");
                                                                                            }


                                                                                            ...We can also make a simple validation like, if it has spaces it cannot be Base64:



                                                                                            String myString = "Hello World";
                                                                                            if(myString.contains(" ")){
                                                                                            System.out.println("Not B64");
                                                                                            }else{
                                                                                            System.out.println("Could be B64 encoded, since it has no spaces");
                                                                                            }





                                                                                            share|improve this answer


























                                                                                            • Ok, could you please give a solution then?

                                                                                              – Marco
                                                                                              Jan 17 at 16:08











                                                                                            • working on it :)

                                                                                              – HIRA THAKUR
                                                                                              Jan 18 at 6:45














                                                                                            -1












                                                                                            -1








                                                                                            -1







                                                                                            Try this using a previously mentioned regex:



                                                                                            String regex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                                                                                            if("TXkgdGVzdCBzdHJpbmc/".matches(regex)){
                                                                                            System.out.println("it's a Base64");
                                                                                            }


                                                                                            ...We can also make a simple validation like, if it has spaces it cannot be Base64:



                                                                                            String myString = "Hello World";
                                                                                            if(myString.contains(" ")){
                                                                                            System.out.println("Not B64");
                                                                                            }else{
                                                                                            System.out.println("Could be B64 encoded, since it has no spaces");
                                                                                            }





                                                                                            share|improve this answer















                                                                                            Try this using a previously mentioned regex:



                                                                                            String regex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
                                                                                            if("TXkgdGVzdCBzdHJpbmc/".matches(regex)){
                                                                                            System.out.println("it's a Base64");
                                                                                            }


                                                                                            ...We can also make a simple validation like, if it has spaces it cannot be Base64:



                                                                                            String myString = "Hello World";
                                                                                            if(myString.contains(" ")){
                                                                                            System.out.println("Not B64");
                                                                                            }else{
                                                                                            System.out.println("Could be B64 encoded, since it has no spaces");
                                                                                            }






                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Jul 8 '16 at 13:52

























                                                                                            answered Jul 7 '16 at 15:57









                                                                                            MarcoMarco

                                                                                            1,13311315




                                                                                            1,13311315













                                                                                            • Ok, could you please give a solution then?

                                                                                              – Marco
                                                                                              Jan 17 at 16:08











                                                                                            • working on it :)

                                                                                              – HIRA THAKUR
                                                                                              Jan 18 at 6:45



















                                                                                            • Ok, could you please give a solution then?

                                                                                              – Marco
                                                                                              Jan 17 at 16:08











                                                                                            • working on it :)

                                                                                              – HIRA THAKUR
                                                                                              Jan 18 at 6:45

















                                                                                            Ok, could you please give a solution then?

                                                                                            – Marco
                                                                                            Jan 17 at 16:08





                                                                                            Ok, could you please give a solution then?

                                                                                            – Marco
                                                                                            Jan 17 at 16:08













                                                                                            working on it :)

                                                                                            – HIRA THAKUR
                                                                                            Jan 18 at 6:45





                                                                                            working on it :)

                                                                                            – HIRA THAKUR
                                                                                            Jan 18 at 6:45


















                                                                                            draft saved

                                                                                            draft discarded




















































                                                                                            Thanks for contributing an answer to Stack Overflow!


                                                                                            • Please be sure to answer the question. Provide details and share your research!

                                                                                            But avoid



                                                                                            • Asking for help, clarification, or responding to other answers.

                                                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                                                            To learn more, see our tips on writing great answers.




                                                                                            draft saved


                                                                                            draft discarded














                                                                                            StackExchange.ready(
                                                                                            function () {
                                                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8571501%2fhow-to-check-whether-a-string-is-base64-encoded-or-not%23new-answer', 'question_page');
                                                                                            }
                                                                                            );

                                                                                            Post as a guest















                                                                                            Required, but never shown





















































                                                                                            Required, but never shown














                                                                                            Required, but never shown












                                                                                            Required, but never shown







                                                                                            Required, but never shown

































                                                                                            Required, but never shown














                                                                                            Required, but never shown












                                                                                            Required, but never shown







                                                                                            Required, but never shown







                                                                                            Popular posts from this blog

                                                                                            Costa Masnaga

                                                                                            Fotorealismo

                                                                                            Sidney Franklin