Remove trailing “=” when base64 encoding












39














I am noticing that whenever I base64 encode a string, a "=" is appended at the end. Can I remove this character and then reliably decode it later by adding it back, or is this dangerous? In other words, is the "=" always appended, or only in certain cases?



I want my encoded string to be as short as possible, that's why I want to know if I can always remove the "=" character and just add it back before decoding.










share|improve this question




















  • 2




    Let's define base64-sensible as base64-without-padding, pretty please? These equals characters are completely redundant and therefore utterly pointless. If you write a base64 decoder, please consider not rejecting inputs that don't have the padding.
    – Roman Starkov
    Dec 3 '13 at 17:09
















39














I am noticing that whenever I base64 encode a string, a "=" is appended at the end. Can I remove this character and then reliably decode it later by adding it back, or is this dangerous? In other words, is the "=" always appended, or only in certain cases?



I want my encoded string to be as short as possible, that's why I want to know if I can always remove the "=" character and just add it back before decoding.










share|improve this question




















  • 2




    Let's define base64-sensible as base64-without-padding, pretty please? These equals characters are completely redundant and therefore utterly pointless. If you write a base64 decoder, please consider not rejecting inputs that don't have the padding.
    – Roman Starkov
    Dec 3 '13 at 17:09














39












39








39


13





I am noticing that whenever I base64 encode a string, a "=" is appended at the end. Can I remove this character and then reliably decode it later by adding it back, or is this dangerous? In other words, is the "=" always appended, or only in certain cases?



I want my encoded string to be as short as possible, that's why I want to know if I can always remove the "=" character and just add it back before decoding.










share|improve this question















I am noticing that whenever I base64 encode a string, a "=" is appended at the end. Can I remove this character and then reliably decode it later by adding it back, or is this dangerous? In other words, is the "=" always appended, or only in certain cases?



I want my encoded string to be as short as possible, that's why I want to know if I can always remove the "=" character and just add it back before decoding.







base64






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 22 '18 at 7:29









thefourtheye

162k26286370




162k26286370










asked Dec 20 '10 at 18:01









Steve N

1,57731833




1,57731833








  • 2




    Let's define base64-sensible as base64-without-padding, pretty please? These equals characters are completely redundant and therefore utterly pointless. If you write a base64 decoder, please consider not rejecting inputs that don't have the padding.
    – Roman Starkov
    Dec 3 '13 at 17:09














  • 2




    Let's define base64-sensible as base64-without-padding, pretty please? These equals characters are completely redundant and therefore utterly pointless. If you write a base64 decoder, please consider not rejecting inputs that don't have the padding.
    – Roman Starkov
    Dec 3 '13 at 17:09








2




2




Let's define base64-sensible as base64-without-padding, pretty please? These equals characters are completely redundant and therefore utterly pointless. If you write a base64 decoder, please consider not rejecting inputs that don't have the padding.
– Roman Starkov
Dec 3 '13 at 17:09




Let's define base64-sensible as base64-without-padding, pretty please? These equals characters are completely redundant and therefore utterly pointless. If you write a base64 decoder, please consider not rejecting inputs that don't have the padding.
– Roman Starkov
Dec 3 '13 at 17:09












6 Answers
6






active

oldest

votes


















54














The = is padding.



Wikipedia says




An additional pad character is
allocated which may be used to force
the encoded output into an integer
multiple of 4 characters (or
equivalently when the unencoded binary
text is not a multiple of 3 bytes) ;
these padding characters must then be
discarded when decoding but still
allow the calculation of the effective
length of the unencoded text, when its
input binary length would not be a
multiple of 3 bytes (the last non-pad
character is normally encoded so that
the last 6-bit block it represents
will be zero-padded on its least
significant bits, at most two pad
characters may occur at the end of the
encoded stream).




If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.

Note that the data will not be valid Base64 in transport.






share|improve this answer























  • Looks like this may not actually work, since at the decoding end we would need to know whether or not the "=" was removed on the encoding end.. I am not able to include that information.
    – Steve N
    Dec 20 '10 at 18:48






  • 41




    @Steve: If the length isn't a multiple of 4 characters, add = characters until it is. In .Net, if (str.Length % 4 != 0) str += new string('=', 4 - str.Length % 4)
    – SLaks
    Dec 20 '10 at 18:50








  • 13




    Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back.
    – Mahn
    Oct 16 '14 at 16:33






  • 2




    Like @Mahn mentioned, even Javascript's atob() function does not need the padding to successfully decode a base64 encoded string
    – Akshay Raje
    Oct 20 '16 at 14:00



















22














I wrote part of Apache's commons-codec-1.4.jar Base64 decoder, and in that logic we are fine without padding characters. End-of-file and End-of-stream are just as good indicators that the Base64 message is finished as any number of '=' characters!



The URL-Safe variant we introduced in commons-codec-1.4 omits the padding characters on purpose to keep things smaller!



http://commons.apache.org/codec/apidocs/src-html/org/apache/commons/codec/binary/Base64.html#line.478



I guess a safer answer is, "depends on your decoder implementation," but logically it is not hard to write a decoder that doesn't need padding.






share|improve this answer

















  • 1




    Interesting- thanks for this perspective. I wonder if the padding was intended to optimize hardware implementations.
    – Steve N
    Jan 26 '11 at 15:00










  • Users should note that if you encode as URL safe and then another program is decoding with something other than Apache, it will not decode correctly.
    – smcg
    Jul 25 '13 at 18:21










  • Url safe also does additional transforms, : encodeUrlSafe(decode("d8vb15jT4MYKb7RpvtJq+/EH8K1h5XH14Oi+3NtrLcM")) = ="d8vb15jT4MYKb7RpvtJq-_EH8K1h5XH14Oi-3NtrLcM" Here you may see that it replaces + with minus and / with _
    – stokito
    Mar 16 '16 at 8:40












  • Yes, of course. + and / are special chars inside URLS and thus not url-safe!
    – Julius Musseau
    Nov 3 '16 at 18:26



















19














In JavaScript you could do something like this:



// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';

// make URL friendly:
str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');

// reverse to original encoding
if (str.length % 4 != 0){
str += ('===').slice(0, 4 - (str.length % 4));
}
str = str.replace(/-/g, '+').replace(/_/g, '/');


See also this Fiddle: http://jsfiddle.net/7bjaT/66/






share|improve this answer































    9














    = is added for padding. The lenght of a base64 string should be multiple of 4, so 1 or 2 = are added as necessary.



    Read: No, you shouldn't remove it.






    share|improve this answer





















    • One useful answer out of all.
      – Exception
      Jan 22 '16 at 12:33










    • So tell me. Why does this not happening to java when encoding Base64 URL safe?
      – Code.IT
      Sep 20 '16 at 7:31










    • @Code.IT "URL safe"? That sounds like a Java function that already trims = characters, because those aren't URL safe.
      – Rudey
      Aug 29 '18 at 12:58










    • = is a padding character. It has nothing to do with URL safe. stackoverflow.com/a/4492448/2739334
      – Code.IT
      Sep 4 '18 at 7:31



















    3














    On Android I am using this:



    Global



    String CHARSET_NAME ="UTF-8";


    Encode



    String base64 = new String(
    Base64.encode(byteArray, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP),
    CHARSET_NAME);
    return base64.trim();


    Decode



    byte bytes = Base64.decode(base64String,
    Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP);


    equals this on Java:



    Encode



    private static String base64UrlEncode(byte input)
    {
    Base64 encoder = new Base64(true);
    byte encodedBytes = encoder.encode(input);
    return StringUtils.newStringUtf8(encodedBytes).trim();
    }


    Decode



    private static byte base64UrlDecode(String input) {
    byte originalValue = StringUtils.getBytesUtf8(input);
    Base64 decoder = new Base64(true);
    return decoder.decode(originalValue);
    }


    I had never problems with trailing "=" and I am using Bouncycastle as well






    share|improve this answer





























      0














      If you're using PHP the following function will revert the stripped string to its original format with proper padding:



      <?php

      $str = 'base64 encoded string without equal signs stripped';
      $str = str_pad($str, strlen($str) + (4 - ((strlen($str) % 4) ?: 4)), '=');

      echo $str, "n";





      share|improve this answer





















        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%2f4492426%2fremove-trailing-when-base64-encoding%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        54














        The = is padding.



        Wikipedia says




        An additional pad character is
        allocated which may be used to force
        the encoded output into an integer
        multiple of 4 characters (or
        equivalently when the unencoded binary
        text is not a multiple of 3 bytes) ;
        these padding characters must then be
        discarded when decoding but still
        allow the calculation of the effective
        length of the unencoded text, when its
        input binary length would not be a
        multiple of 3 bytes (the last non-pad
        character is normally encoded so that
        the last 6-bit block it represents
        will be zero-padded on its least
        significant bits, at most two pad
        characters may occur at the end of the
        encoded stream).




        If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.

        Note that the data will not be valid Base64 in transport.






        share|improve this answer























        • Looks like this may not actually work, since at the decoding end we would need to know whether or not the "=" was removed on the encoding end.. I am not able to include that information.
          – Steve N
          Dec 20 '10 at 18:48






        • 41




          @Steve: If the length isn't a multiple of 4 characters, add = characters until it is. In .Net, if (str.Length % 4 != 0) str += new string('=', 4 - str.Length % 4)
          – SLaks
          Dec 20 '10 at 18:50








        • 13




          Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back.
          – Mahn
          Oct 16 '14 at 16:33






        • 2




          Like @Mahn mentioned, even Javascript's atob() function does not need the padding to successfully decode a base64 encoded string
          – Akshay Raje
          Oct 20 '16 at 14:00
















        54














        The = is padding.



        Wikipedia says




        An additional pad character is
        allocated which may be used to force
        the encoded output into an integer
        multiple of 4 characters (or
        equivalently when the unencoded binary
        text is not a multiple of 3 bytes) ;
        these padding characters must then be
        discarded when decoding but still
        allow the calculation of the effective
        length of the unencoded text, when its
        input binary length would not be a
        multiple of 3 bytes (the last non-pad
        character is normally encoded so that
        the last 6-bit block it represents
        will be zero-padded on its least
        significant bits, at most two pad
        characters may occur at the end of the
        encoded stream).




        If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.

        Note that the data will not be valid Base64 in transport.






        share|improve this answer























        • Looks like this may not actually work, since at the decoding end we would need to know whether or not the "=" was removed on the encoding end.. I am not able to include that information.
          – Steve N
          Dec 20 '10 at 18:48






        • 41




          @Steve: If the length isn't a multiple of 4 characters, add = characters until it is. In .Net, if (str.Length % 4 != 0) str += new string('=', 4 - str.Length % 4)
          – SLaks
          Dec 20 '10 at 18:50








        • 13




          Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back.
          – Mahn
          Oct 16 '14 at 16:33






        • 2




          Like @Mahn mentioned, even Javascript's atob() function does not need the padding to successfully decode a base64 encoded string
          – Akshay Raje
          Oct 20 '16 at 14:00














        54












        54








        54






        The = is padding.



        Wikipedia says




        An additional pad character is
        allocated which may be used to force
        the encoded output into an integer
        multiple of 4 characters (or
        equivalently when the unencoded binary
        text is not a multiple of 3 bytes) ;
        these padding characters must then be
        discarded when decoding but still
        allow the calculation of the effective
        length of the unencoded text, when its
        input binary length would not be a
        multiple of 3 bytes (the last non-pad
        character is normally encoded so that
        the last 6-bit block it represents
        will be zero-padded on its least
        significant bits, at most two pad
        characters may occur at the end of the
        encoded stream).




        If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.

        Note that the data will not be valid Base64 in transport.






        share|improve this answer














        The = is padding.



        Wikipedia says




        An additional pad character is
        allocated which may be used to force
        the encoded output into an integer
        multiple of 4 characters (or
        equivalently when the unencoded binary
        text is not a multiple of 3 bytes) ;
        these padding characters must then be
        discarded when decoding but still
        allow the calculation of the effective
        length of the unencoded text, when its
        input binary length would not be a
        multiple of 3 bytes (the last non-pad
        character is normally encoded so that
        the last 6-bit block it represents
        will be zero-padded on its least
        significant bits, at most two pad
        characters may occur at the end of the
        encoded stream).




        If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.

        Note that the data will not be valid Base64 in transport.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 20 '10 at 18:06

























        answered Dec 20 '10 at 18:04









        SLaks

        678k13916281751




        678k13916281751












        • Looks like this may not actually work, since at the decoding end we would need to know whether or not the "=" was removed on the encoding end.. I am not able to include that information.
          – Steve N
          Dec 20 '10 at 18:48






        • 41




          @Steve: If the length isn't a multiple of 4 characters, add = characters until it is. In .Net, if (str.Length % 4 != 0) str += new string('=', 4 - str.Length % 4)
          – SLaks
          Dec 20 '10 at 18:50








        • 13




          Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back.
          – Mahn
          Oct 16 '14 at 16:33






        • 2




          Like @Mahn mentioned, even Javascript's atob() function does not need the padding to successfully decode a base64 encoded string
          – Akshay Raje
          Oct 20 '16 at 14:00


















        • Looks like this may not actually work, since at the decoding end we would need to know whether or not the "=" was removed on the encoding end.. I am not able to include that information.
          – Steve N
          Dec 20 '10 at 18:48






        • 41




          @Steve: If the length isn't a multiple of 4 characters, add = characters until it is. In .Net, if (str.Length % 4 != 0) str += new string('=', 4 - str.Length % 4)
          – SLaks
          Dec 20 '10 at 18:50








        • 13




          Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back.
          – Mahn
          Oct 16 '14 at 16:33






        • 2




          Like @Mahn mentioned, even Javascript's atob() function does not need the padding to successfully decode a base64 encoded string
          – Akshay Raje
          Oct 20 '16 at 14:00
















        Looks like this may not actually work, since at the decoding end we would need to know whether or not the "=" was removed on the encoding end.. I am not able to include that information.
        – Steve N
        Dec 20 '10 at 18:48




        Looks like this may not actually work, since at the decoding end we would need to know whether or not the "=" was removed on the encoding end.. I am not able to include that information.
        – Steve N
        Dec 20 '10 at 18:48




        41




        41




        @Steve: If the length isn't a multiple of 4 characters, add = characters until it is. In .Net, if (str.Length % 4 != 0) str += new string('=', 4 - str.Length % 4)
        – SLaks
        Dec 20 '10 at 18:50






        @Steve: If the length isn't a multiple of 4 characters, add = characters until it is. In .Net, if (str.Length % 4 != 0) str += new string('=', 4 - str.Length % 4)
        – SLaks
        Dec 20 '10 at 18:50






        13




        13




        Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back.
        – Mahn
        Oct 16 '14 at 16:33




        Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back.
        – Mahn
        Oct 16 '14 at 16:33




        2




        2




        Like @Mahn mentioned, even Javascript's atob() function does not need the padding to successfully decode a base64 encoded string
        – Akshay Raje
        Oct 20 '16 at 14:00




        Like @Mahn mentioned, even Javascript's atob() function does not need the padding to successfully decode a base64 encoded string
        – Akshay Raje
        Oct 20 '16 at 14:00













        22














        I wrote part of Apache's commons-codec-1.4.jar Base64 decoder, and in that logic we are fine without padding characters. End-of-file and End-of-stream are just as good indicators that the Base64 message is finished as any number of '=' characters!



        The URL-Safe variant we introduced in commons-codec-1.4 omits the padding characters on purpose to keep things smaller!



        http://commons.apache.org/codec/apidocs/src-html/org/apache/commons/codec/binary/Base64.html#line.478



        I guess a safer answer is, "depends on your decoder implementation," but logically it is not hard to write a decoder that doesn't need padding.






        share|improve this answer

















        • 1




          Interesting- thanks for this perspective. I wonder if the padding was intended to optimize hardware implementations.
          – Steve N
          Jan 26 '11 at 15:00










        • Users should note that if you encode as URL safe and then another program is decoding with something other than Apache, it will not decode correctly.
          – smcg
          Jul 25 '13 at 18:21










        • Url safe also does additional transforms, : encodeUrlSafe(decode("d8vb15jT4MYKb7RpvtJq+/EH8K1h5XH14Oi+3NtrLcM")) = ="d8vb15jT4MYKb7RpvtJq-_EH8K1h5XH14Oi-3NtrLcM" Here you may see that it replaces + with minus and / with _
          – stokito
          Mar 16 '16 at 8:40












        • Yes, of course. + and / are special chars inside URLS and thus not url-safe!
          – Julius Musseau
          Nov 3 '16 at 18:26
















        22














        I wrote part of Apache's commons-codec-1.4.jar Base64 decoder, and in that logic we are fine without padding characters. End-of-file and End-of-stream are just as good indicators that the Base64 message is finished as any number of '=' characters!



        The URL-Safe variant we introduced in commons-codec-1.4 omits the padding characters on purpose to keep things smaller!



        http://commons.apache.org/codec/apidocs/src-html/org/apache/commons/codec/binary/Base64.html#line.478



        I guess a safer answer is, "depends on your decoder implementation," but logically it is not hard to write a decoder that doesn't need padding.






        share|improve this answer

















        • 1




          Interesting- thanks for this perspective. I wonder if the padding was intended to optimize hardware implementations.
          – Steve N
          Jan 26 '11 at 15:00










        • Users should note that if you encode as URL safe and then another program is decoding with something other than Apache, it will not decode correctly.
          – smcg
          Jul 25 '13 at 18:21










        • Url safe also does additional transforms, : encodeUrlSafe(decode("d8vb15jT4MYKb7RpvtJq+/EH8K1h5XH14Oi+3NtrLcM")) = ="d8vb15jT4MYKb7RpvtJq-_EH8K1h5XH14Oi-3NtrLcM" Here you may see that it replaces + with minus and / with _
          – stokito
          Mar 16 '16 at 8:40












        • Yes, of course. + and / are special chars inside URLS and thus not url-safe!
          – Julius Musseau
          Nov 3 '16 at 18:26














        22












        22








        22






        I wrote part of Apache's commons-codec-1.4.jar Base64 decoder, and in that logic we are fine without padding characters. End-of-file and End-of-stream are just as good indicators that the Base64 message is finished as any number of '=' characters!



        The URL-Safe variant we introduced in commons-codec-1.4 omits the padding characters on purpose to keep things smaller!



        http://commons.apache.org/codec/apidocs/src-html/org/apache/commons/codec/binary/Base64.html#line.478



        I guess a safer answer is, "depends on your decoder implementation," but logically it is not hard to write a decoder that doesn't need padding.






        share|improve this answer












        I wrote part of Apache's commons-codec-1.4.jar Base64 decoder, and in that logic we are fine without padding characters. End-of-file and End-of-stream are just as good indicators that the Base64 message is finished as any number of '=' characters!



        The URL-Safe variant we introduced in commons-codec-1.4 omits the padding characters on purpose to keep things smaller!



        http://commons.apache.org/codec/apidocs/src-html/org/apache/commons/codec/binary/Base64.html#line.478



        I guess a safer answer is, "depends on your decoder implementation," but logically it is not hard to write a decoder that doesn't need padding.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 25 '11 at 19:21









        Julius Musseau

        3,0951522




        3,0951522








        • 1




          Interesting- thanks for this perspective. I wonder if the padding was intended to optimize hardware implementations.
          – Steve N
          Jan 26 '11 at 15:00










        • Users should note that if you encode as URL safe and then another program is decoding with something other than Apache, it will not decode correctly.
          – smcg
          Jul 25 '13 at 18:21










        • Url safe also does additional transforms, : encodeUrlSafe(decode("d8vb15jT4MYKb7RpvtJq+/EH8K1h5XH14Oi+3NtrLcM")) = ="d8vb15jT4MYKb7RpvtJq-_EH8K1h5XH14Oi-3NtrLcM" Here you may see that it replaces + with minus and / with _
          – stokito
          Mar 16 '16 at 8:40












        • Yes, of course. + and / are special chars inside URLS and thus not url-safe!
          – Julius Musseau
          Nov 3 '16 at 18:26














        • 1




          Interesting- thanks for this perspective. I wonder if the padding was intended to optimize hardware implementations.
          – Steve N
          Jan 26 '11 at 15:00










        • Users should note that if you encode as URL safe and then another program is decoding with something other than Apache, it will not decode correctly.
          – smcg
          Jul 25 '13 at 18:21










        • Url safe also does additional transforms, : encodeUrlSafe(decode("d8vb15jT4MYKb7RpvtJq+/EH8K1h5XH14Oi+3NtrLcM")) = ="d8vb15jT4MYKb7RpvtJq-_EH8K1h5XH14Oi-3NtrLcM" Here you may see that it replaces + with minus and / with _
          – stokito
          Mar 16 '16 at 8:40












        • Yes, of course. + and / are special chars inside URLS and thus not url-safe!
          – Julius Musseau
          Nov 3 '16 at 18:26








        1




        1




        Interesting- thanks for this perspective. I wonder if the padding was intended to optimize hardware implementations.
        – Steve N
        Jan 26 '11 at 15:00




        Interesting- thanks for this perspective. I wonder if the padding was intended to optimize hardware implementations.
        – Steve N
        Jan 26 '11 at 15:00












        Users should note that if you encode as URL safe and then another program is decoding with something other than Apache, it will not decode correctly.
        – smcg
        Jul 25 '13 at 18:21




        Users should note that if you encode as URL safe and then another program is decoding with something other than Apache, it will not decode correctly.
        – smcg
        Jul 25 '13 at 18:21












        Url safe also does additional transforms, : encodeUrlSafe(decode("d8vb15jT4MYKb7RpvtJq+/EH8K1h5XH14Oi+3NtrLcM")) = ="d8vb15jT4MYKb7RpvtJq-_EH8K1h5XH14Oi-3NtrLcM" Here you may see that it replaces + with minus and / with _
        – stokito
        Mar 16 '16 at 8:40






        Url safe also does additional transforms, : encodeUrlSafe(decode("d8vb15jT4MYKb7RpvtJq+/EH8K1h5XH14Oi+3NtrLcM")) = ="d8vb15jT4MYKb7RpvtJq-_EH8K1h5XH14Oi-3NtrLcM" Here you may see that it replaces + with minus and / with _
        – stokito
        Mar 16 '16 at 8:40














        Yes, of course. + and / are special chars inside URLS and thus not url-safe!
        – Julius Musseau
        Nov 3 '16 at 18:26




        Yes, of course. + and / are special chars inside URLS and thus not url-safe!
        – Julius Musseau
        Nov 3 '16 at 18:26











        19














        In JavaScript you could do something like this:



        // if this is your Base64 encoded string
        var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';

        // make URL friendly:
        str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');

        // reverse to original encoding
        if (str.length % 4 != 0){
        str += ('===').slice(0, 4 - (str.length % 4));
        }
        str = str.replace(/-/g, '+').replace(/_/g, '/');


        See also this Fiddle: http://jsfiddle.net/7bjaT/66/






        share|improve this answer




























          19














          In JavaScript you could do something like this:



          // if this is your Base64 encoded string
          var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';

          // make URL friendly:
          str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');

          // reverse to original encoding
          if (str.length % 4 != 0){
          str += ('===').slice(0, 4 - (str.length % 4));
          }
          str = str.replace(/-/g, '+').replace(/_/g, '/');


          See also this Fiddle: http://jsfiddle.net/7bjaT/66/






          share|improve this answer


























            19












            19








            19






            In JavaScript you could do something like this:



            // if this is your Base64 encoded string
            var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';

            // make URL friendly:
            str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');

            // reverse to original encoding
            if (str.length % 4 != 0){
            str += ('===').slice(0, 4 - (str.length % 4));
            }
            str = str.replace(/-/g, '+').replace(/_/g, '/');


            See also this Fiddle: http://jsfiddle.net/7bjaT/66/






            share|improve this answer














            In JavaScript you could do something like this:



            // if this is your Base64 encoded string
            var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';

            // make URL friendly:
            str = str.replace(/+/g, '-').replace(///g, '_').replace(/=+$/, '');

            // reverse to original encoding
            if (str.length % 4 != 0){
            str += ('===').slice(0, 4 - (str.length % 4));
            }
            str = str.replace(/-/g, '+').replace(/_/g, '/');


            See also this Fiddle: http://jsfiddle.net/7bjaT/66/







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 19 '18 at 17:11

























            answered Aug 21 '11 at 15:33









            magikMaker

            1,0181112




            1,0181112























                9














                = is added for padding. The lenght of a base64 string should be multiple of 4, so 1 or 2 = are added as necessary.



                Read: No, you shouldn't remove it.






                share|improve this answer





















                • One useful answer out of all.
                  – Exception
                  Jan 22 '16 at 12:33










                • So tell me. Why does this not happening to java when encoding Base64 URL safe?
                  – Code.IT
                  Sep 20 '16 at 7:31










                • @Code.IT "URL safe"? That sounds like a Java function that already trims = characters, because those aren't URL safe.
                  – Rudey
                  Aug 29 '18 at 12:58










                • = is a padding character. It has nothing to do with URL safe. stackoverflow.com/a/4492448/2739334
                  – Code.IT
                  Sep 4 '18 at 7:31
















                9














                = is added for padding. The lenght of a base64 string should be multiple of 4, so 1 or 2 = are added as necessary.



                Read: No, you shouldn't remove it.






                share|improve this answer





















                • One useful answer out of all.
                  – Exception
                  Jan 22 '16 at 12:33










                • So tell me. Why does this not happening to java when encoding Base64 URL safe?
                  – Code.IT
                  Sep 20 '16 at 7:31










                • @Code.IT "URL safe"? That sounds like a Java function that already trims = characters, because those aren't URL safe.
                  – Rudey
                  Aug 29 '18 at 12:58










                • = is a padding character. It has nothing to do with URL safe. stackoverflow.com/a/4492448/2739334
                  – Code.IT
                  Sep 4 '18 at 7:31














                9












                9








                9






                = is added for padding. The lenght of a base64 string should be multiple of 4, so 1 or 2 = are added as necessary.



                Read: No, you shouldn't remove it.






                share|improve this answer












                = is added for padding. The lenght of a base64 string should be multiple of 4, so 1 or 2 = are added as necessary.



                Read: No, you shouldn't remove it.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 20 '10 at 18:04









                Juan Pablo Califano

                10.6k32538




                10.6k32538












                • One useful answer out of all.
                  – Exception
                  Jan 22 '16 at 12:33










                • So tell me. Why does this not happening to java when encoding Base64 URL safe?
                  – Code.IT
                  Sep 20 '16 at 7:31










                • @Code.IT "URL safe"? That sounds like a Java function that already trims = characters, because those aren't URL safe.
                  – Rudey
                  Aug 29 '18 at 12:58










                • = is a padding character. It has nothing to do with URL safe. stackoverflow.com/a/4492448/2739334
                  – Code.IT
                  Sep 4 '18 at 7:31


















                • One useful answer out of all.
                  – Exception
                  Jan 22 '16 at 12:33










                • So tell me. Why does this not happening to java when encoding Base64 URL safe?
                  – Code.IT
                  Sep 20 '16 at 7:31










                • @Code.IT "URL safe"? That sounds like a Java function that already trims = characters, because those aren't URL safe.
                  – Rudey
                  Aug 29 '18 at 12:58










                • = is a padding character. It has nothing to do with URL safe. stackoverflow.com/a/4492448/2739334
                  – Code.IT
                  Sep 4 '18 at 7:31
















                One useful answer out of all.
                – Exception
                Jan 22 '16 at 12:33




                One useful answer out of all.
                – Exception
                Jan 22 '16 at 12:33












                So tell me. Why does this not happening to java when encoding Base64 URL safe?
                – Code.IT
                Sep 20 '16 at 7:31




                So tell me. Why does this not happening to java when encoding Base64 URL safe?
                – Code.IT
                Sep 20 '16 at 7:31












                @Code.IT "URL safe"? That sounds like a Java function that already trims = characters, because those aren't URL safe.
                – Rudey
                Aug 29 '18 at 12:58




                @Code.IT "URL safe"? That sounds like a Java function that already trims = characters, because those aren't URL safe.
                – Rudey
                Aug 29 '18 at 12:58












                = is a padding character. It has nothing to do with URL safe. stackoverflow.com/a/4492448/2739334
                – Code.IT
                Sep 4 '18 at 7:31




                = is a padding character. It has nothing to do with URL safe. stackoverflow.com/a/4492448/2739334
                – Code.IT
                Sep 4 '18 at 7:31











                3














                On Android I am using this:



                Global



                String CHARSET_NAME ="UTF-8";


                Encode



                String base64 = new String(
                Base64.encode(byteArray, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP),
                CHARSET_NAME);
                return base64.trim();


                Decode



                byte bytes = Base64.decode(base64String,
                Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP);


                equals this on Java:



                Encode



                private static String base64UrlEncode(byte input)
                {
                Base64 encoder = new Base64(true);
                byte encodedBytes = encoder.encode(input);
                return StringUtils.newStringUtf8(encodedBytes).trim();
                }


                Decode



                private static byte base64UrlDecode(String input) {
                byte originalValue = StringUtils.getBytesUtf8(input);
                Base64 decoder = new Base64(true);
                return decoder.decode(originalValue);
                }


                I had never problems with trailing "=" and I am using Bouncycastle as well






                share|improve this answer


























                  3














                  On Android I am using this:



                  Global



                  String CHARSET_NAME ="UTF-8";


                  Encode



                  String base64 = new String(
                  Base64.encode(byteArray, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP),
                  CHARSET_NAME);
                  return base64.trim();


                  Decode



                  byte bytes = Base64.decode(base64String,
                  Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP);


                  equals this on Java:



                  Encode



                  private static String base64UrlEncode(byte input)
                  {
                  Base64 encoder = new Base64(true);
                  byte encodedBytes = encoder.encode(input);
                  return StringUtils.newStringUtf8(encodedBytes).trim();
                  }


                  Decode



                  private static byte base64UrlDecode(String input) {
                  byte originalValue = StringUtils.getBytesUtf8(input);
                  Base64 decoder = new Base64(true);
                  return decoder.decode(originalValue);
                  }


                  I had never problems with trailing "=" and I am using Bouncycastle as well






                  share|improve this answer
























                    3












                    3








                    3






                    On Android I am using this:



                    Global



                    String CHARSET_NAME ="UTF-8";


                    Encode



                    String base64 = new String(
                    Base64.encode(byteArray, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP),
                    CHARSET_NAME);
                    return base64.trim();


                    Decode



                    byte bytes = Base64.decode(base64String,
                    Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP);


                    equals this on Java:



                    Encode



                    private static String base64UrlEncode(byte input)
                    {
                    Base64 encoder = new Base64(true);
                    byte encodedBytes = encoder.encode(input);
                    return StringUtils.newStringUtf8(encodedBytes).trim();
                    }


                    Decode



                    private static byte base64UrlDecode(String input) {
                    byte originalValue = StringUtils.getBytesUtf8(input);
                    Base64 decoder = new Base64(true);
                    return decoder.decode(originalValue);
                    }


                    I had never problems with trailing "=" and I am using Bouncycastle as well






                    share|improve this answer












                    On Android I am using this:



                    Global



                    String CHARSET_NAME ="UTF-8";


                    Encode



                    String base64 = new String(
                    Base64.encode(byteArray, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP),
                    CHARSET_NAME);
                    return base64.trim();


                    Decode



                    byte bytes = Base64.decode(base64String,
                    Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP);


                    equals this on Java:



                    Encode



                    private static String base64UrlEncode(byte input)
                    {
                    Base64 encoder = new Base64(true);
                    byte encodedBytes = encoder.encode(input);
                    return StringUtils.newStringUtf8(encodedBytes).trim();
                    }


                    Decode



                    private static byte base64UrlDecode(String input) {
                    byte originalValue = StringUtils.getBytesUtf8(input);
                    Base64 decoder = new Base64(true);
                    return decoder.decode(originalValue);
                    }


                    I had never problems with trailing "=" and I am using Bouncycastle as well







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Oct 6 '16 at 10:46









                    Code.IT

                    1,14211528




                    1,14211528























                        0














                        If you're using PHP the following function will revert the stripped string to its original format with proper padding:



                        <?php

                        $str = 'base64 encoded string without equal signs stripped';
                        $str = str_pad($str, strlen($str) + (4 - ((strlen($str) % 4) ?: 4)), '=');

                        echo $str, "n";





                        share|improve this answer


























                          0














                          If you're using PHP the following function will revert the stripped string to its original format with proper padding:



                          <?php

                          $str = 'base64 encoded string without equal signs stripped';
                          $str = str_pad($str, strlen($str) + (4 - ((strlen($str) % 4) ?: 4)), '=');

                          echo $str, "n";





                          share|improve this answer
























                            0












                            0








                            0






                            If you're using PHP the following function will revert the stripped string to its original format with proper padding:



                            <?php

                            $str = 'base64 encoded string without equal signs stripped';
                            $str = str_pad($str, strlen($str) + (4 - ((strlen($str) % 4) ?: 4)), '=');

                            echo $str, "n";





                            share|improve this answer












                            If you're using PHP the following function will revert the stripped string to its original format with proper padding:



                            <?php

                            $str = 'base64 encoded string without equal signs stripped';
                            $str = str_pad($str, strlen($str) + (4 - ((strlen($str) % 4) ?: 4)), '=');

                            echo $str, "n";






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Oct 30 '18 at 17:51









                            supersan

                            1,6261633




                            1,6261633






























                                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.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • 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%2f4492426%2fremove-trailing-when-base64-encoding%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

                                android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                                SQL update select statement

                                'app-layout' is not a known element: how to share Component with different Modules