Base64 encode and decode in php

How do I convert a base64 string?

I was using a downloaded PHP template, and when I was well into manipulating it, I realize part of it had been encrypted in what appears to be base64. I tried a few online converts, with little luck. I have this bit of code, followed by a ton of random characters outside the tags:

$O000O0O00=fopen($OOO0O0O00,'rb');while(--$O00O00O00)fgets($O000O0O00,1024);fgets($O000O0O00,4096);$OO00O00O0=(base64_decode(strtr(fread($O000O0O00,372),'3safZjG54HFqMdLAOg9wbIzPR/plK8+7eUcxQBWmY1uS6NXrhvDCnt0E2ToJkViy=','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')));eval($OO00O00O0); 

However, below that I have this code: http://pastebin.com/Z2uMwS9C I have no clue how to convert it. Any ideas? I think the segments of code are too long — I tried to use Notepad++ to convert it, and it basically said it was too long. Thanks.

That’s definitely malicious code injected by the site you got it from. How about looking for the original download, or at least a link to a legitimate download site?

yeah. I just found a different download site, and it was clear. But I am still curious as to its contents?

Many template authors insert their copyright info in base64 encoded blocks, somewhat legitimately. But fwrite() statements in such a block would make me very nervous, too.

1 Answer 1

Here’s my decompressed version of what we have so far:

 /* Move the file cursor just a wee bit more, presumably to where the other data starts. */ fgets($this_file_handle,4096); /* Read in the remaining data, run it through a character replacing function (3 --> A, s --> B, etc.), and base64-decode the result. */ $probably_malicious_code = ( base64_decode( strtr( fread($this_file_handle,372), '3safZjG54HFqMdLAOg9wbIzPR/plK8+7eUcxQBWmY1uS6NXrhvDCnt0E2ToJkViy=', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' ) ) ); /* Run the probably-evil code. */ eval($probably_malicious_code); 

If we use echo instead of eval at the last line, we get this, a third level of obfuscation.

Читайте также:  Display css code in html

I N C E P T I O N

Here’s a script that’s equivalent to what’s going on at Level 3:

 fgets($this_file_handle,4096); /* Level 3 decoding: */ $level_three_code = ereg_replace( '__FILE__', "'".$this_file."'", // base64_decode( strtr( fread($this_file_handle, $level_three_read_amount), '3safZjG54HFqMdLAOg9wbIzPR/plK8+7eUcxQBWmY1uS6NXrhvDCnt0E2ToJkViy=', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' ) ) ); fclose($this_file_handle); eval($level_three_code); 

Echoing instead of evaluating the last line this time produces something close to our final effect:

    ‘; if ( !function_exists(‘dynamic_sidebar’)|| !dynamic_sidebar(‘footer_sidebar_3’) ) : ;echo ‘

    ‘; _e(‘Categories’); ;echo ‘

      ‘; wp_list_cats(‘sort_column=name&hierarchical=0’); ;echo ‘
      » ;echo ‘ ‘; if ( !function_exists( ‘dynamic_sidebar’ ) || !dynamic_sidebar( ‘footer_sidebar’ ) ) : ;echo ‘

        ‘; _e( ‘Pages’ ); ;echo ‘

          ‘; wp_list_pages( ‘depth=0&title_li=’ ); ;echo ‘
          » ;echo ‘ ‘; if ( !function_exists( ‘dynamic_sidebar’ ) || !dynamic_sidebar( ‘footer_sidebar_2’ ) ) : ;echo ‘

          ‘; _e( ‘Search’, ‘traction’ ); ;echo ‘

          ‘; if (is_file(STYLESHEETPATH . ‘/searchform.php’ )) include (STYLESHEETPATH . ‘/searchform.php’ ); else include(TEMPLATEPATH . ‘/searchform.php’ ); ;echo ‘ ‘; endif; ;echo ‘ ‘; if ( is_active_sidebar( ‘footer_sidebar_2’ ) ) echo »

        It’s a bit cut off for some reason, but it looks like the idea is just to include copyright while making it ridiculously difficult for you to find it. This is sketchy business; remove this code.

        Источник

        base64_decode

        If the strict parameter is set to true then the base64_decode() function will return false if the input contains character from outside the base64 alphabet. Otherwise invalid characters will be silently discarded.

        Return Values

        Returns the decoded data or false on failure. The returned data may be binary.

        Examples

        Example #1 base64_decode() example

        The above example will output:

        This is an encoded string

        See Also

        User Contributed Notes 17 notes

        If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

        $encodedData = str_replace ( ‘ ‘ , ‘+’ , $encodedData );
        $decocedData = base64_decode ( $encodedData );
        ?>

        I had some trouble trying to let base64_decode decode base64-strings longer than ~5k chars.

        The base64-decoding function is a homomorphism between modulo 4 and modulo 3-length segmented strings. That motivates a divide and conquer approach: Split the encoded string into substrings counting modulo 4 chars, then decode each substring and concatenate all of them.

        $decoded = «» ;
        for ( $i = 0 ; $i < ceil ( strlen ( $encoded )/ 256 ); $i ++)
        $decoded = $decoded . base64_decode ( substr ( $encoded , $i * 256 , 256 ));
        ?>

        where 256 can be replaced by a sufficiently small modulo 4 natural.

        This function supports «base64url» as described in Section 5 of RFC 4648, «Base 64 Encoding with URL and Filename Safe Alphabet»

        function base64url_decode ( $base64url )
        $base64 = strtr ( $base64url , ‘-_’ , ‘+/’ );
        $plainText = base64_decode ( $base64 );
        return ( $plainText );
        >
        ?>

        Base64 for URL parameters/filenames, that adhere to RFC 4648.
        Defaults to dropping the padding on encode since it’s not required for decoding, and keeps the URL free of % encodings.

        function base64url_encode ( $data , $pad = null ) $data = str_replace (array( ‘+’ , ‘/’ ), array( ‘-‘ , ‘_’ ), base64_encode ( $data ));
        if (! $pad ) $data = rtrim ( $data , ‘=’ );
        >
        return $data ;
        >
        function base64url_decode ( $data ) return base64_decode ( str_replace (array( ‘-‘ , ‘_’ ), array( ‘+’ , ‘/’ ), $data ));
        >

        @morgangalpin att gmail dotty com

        A better implementation would be the following regular expression:

        Which will also detect the usage of = or == at the end of the string (and only end).

        If this regex isn’t following proper RFC guidelines, please comment on it.

        A function geared specifically toward this:

        function is_base64_encoded ()
        if ( preg_match ( ‘%^[a-zA-Z0-9/+]*=$%’ , $data )) return TRUE ;
        > else return FALSE ;
        >
        >;

        is_base64_encoded ( «iash21iawhdj98UH3» ); // true
        is_base64_encoded ( «#iu3498r» ); // false
        is_base64_encoded ( «asiudfh9w=8uihf» ); // false
        is_base64_encoded ( «a398UIhnj43f/1!+sadfh3w84hduihhjw= keyword»>); // true

        To follow up on Starson’s post, PHP was changed to no longer treat a space as if it were a plus sign in CVS revision 1.43.2.1, which corresponds to PHP 5.1.0. You can see what happened with a diff to branch point 1.43 at:

        The CVS log indicates that this change was made to fix bug #34214 (base64_decode() does not properly ignore whitespace).

        It would seem from the comment preceding the code which was removed that the treatment of the space as if it were the plus sign was actually intentional at one time:

        When Base64 gets POSTed, all pluses are interpreted as spaces.
        This line changes them back. It’s not exactly the Base64 spec,
        but it is completely compatible with it (the spec says that spaces
        are invalid). This will also save many people considerable
        headache.

        However, RFC 3548 states that characters not in the Base64 alphabet should either be ignored or cause the implementation to reject the encoding and RFC 2045 says they should be ignored. So the original code was unfortunately not fully compatible with the spec or other implementations. It may have also masked problems with code not properly escaping POST variables.

        The change took place between 5.0.5 and 5.1.0. Exactly where I don’t know or care.

        In short php = 5.1.0’s base64_decode( $string ) will no longer make that assumption. I did not see this noted in the change log.

        Please note that, as of this writing, mb_convert_encoding( $string, «UTF-8», «BASE64» ) still behaves as base64_decode( $string ) did in php

        I was wondering how to decode attached images within mails. Basically they are mostly JPEG files, so it was obviously to write a function that decodes JPEG images.
        I guess the plainest way to do so was the following:

        function base64_to_jpeg ( $inputfile , $outputfile ) <
        /* read data (binary) */
        $ifp = fopen ( $inputfile , «rb» );
        $imageData = fread ( $ifp , filesize ( $inputfile ) );
        fclose ( $ifp );
        /* encode & write data (binary) */
        $ifp = fopen ( $outputfile , «wb» );
        fwrite ( $ifp , base64_decode ( $imageData ) );
        fclose ( $ifp );
        /* return output filename */
        return( $outputfile );
        >
        ?>

        This function decodes the given inputfile (a filename!) and saves it to the given outputfile (a filename as well) and then returns the output filename for further usage (e.g. redirect, imagejpeg() and so on).
        I thought that might be helpful.

        Источник

Оцените статью