Author Topic: [Perl] Obfuscated code reformatting  (Read 435 times)

0 Members and 1 Guest are viewing this topic.

Offline Freak

  • /dev/null
  • *
  • Posts: 17
  • Cookies: 3
    • View Profile
[Perl] Obfuscated code reformatting
« on: March 21, 2015, 03:16:02 am »
Hello,

Sometimes you'll open the source code to a website and try to understand how things were done only to find some garbled mass of garbage like this from Google's home page:
http://pastebin.com/cFuPtgiv

This program will help with that a bit by reformatting the code into something a little more readable like this:
http://pastebin.com/t7e8XVUx
On that page it still might look a little bad in some places but that's because the lines are longer than the width of the paste box. Also, a lot of places obfuscate their code on purpose to keep people from understanding it, so even though this is now formatted nicely it's still very confusing.

This'll only work on "curly bracket" languages that use semicolons (Java, C/++, Javascript, etc...) though, and it also messes up things that would usually be 1 line even though they have curly brackets. An example in Java is:
Code: [Select]
int[] array = {1,2,3};
Which would be turned into:
Code: [Select]
int[] array = {
   1,2,3
}
;

Code: [Select]
#!/usr/bin/perl -w
use strict;
my($fname);
my $code = "";
my $tabs = -1;

print "File name: ";
chomp($fname = <STDIN>);
open UNFORM, "<$fname";
foreach(<UNFORM>){
   $code .= $_;
}
close UNFORM;

$code =~ s/\n//g;   #Remove all formating.
$code =~ s/\t//g;   #That way I don't have to check for it to make sure I don't fuck it up.
my @arr = split('', $code);
push(@arr, "\n");   #Avoid index out of bounds in the following loop.
for(my $i = 0; $i<scalar(@arr); ++$i){
   if($arr[$i] eq '{'){
      ++$tabs;
      $arr[$i] = "{\n";
      for(my $e = 0;$e<=$tabs;++$e){$arr[$i] .= "\t"}
   }elsif($arr[$i] eq '}'){
      --$tabs;
      $arr[$i] = "}\n";
      for(my $e = 0;$e<=$tabs;++$e){$arr[$i] .= "\t"}
   }elsif($arr[$i] eq ';'){
      $arr[$i] = ";\n";
      if($arr[$i+1] eq '}'){
         for(my $e = 0;$e<$tabs;++$e){$arr[$i] .= "\t"}
      }else{
         for(my $e = 0;$e<=$tabs;++$e){$arr[$i] .= "\t"}
      }
   }
}
$fname =~ s/\./2\./;
open FORM, ">$fname";
print FORM join('', @arr);
close FORM;
« Last Edit: March 21, 2015, 06:11:45 am by Freak »