Skip to content

Instantly share code, notes, and snippets.

@Moudoux
Created April 16, 2017 20:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Moudoux/904c0219b7dee36cd075033496fec96a to your computer and use it in GitHub Desktop.
Save Moudoux/904c0219b7dee36cd075033496fec96a to your computer and use it in GitHub Desktop.
Simple string obfuscation for .java files
<?php
/*
Simple java string encryption
*/
// The function to encrypt, you can put the encrypt function in each class too.
$encrypt_function = 'Crypto.decrypt';
// Your main client class
$packages = 'Main.java';
// The packages to obfuscate, regex.
$packages .= ',Mods\/([A-Z])\w+\.java';
function encrypt($str) {
// Your encrypt code
return '"'.$str.'"';
}
function decrypt($str) {
// Your decrypt code
return '"'.$str.'"';
}
function deObfuscate($file) {
global $encrypt_function;
$contents = file_get_contents($file);
if (strpos($contents,$encrypt_function) === false) {
echo 'File '.$file.' is not obfuscated'.PHP_EOL;
return;
}
echo 'Deobfuscating file '.$file.' {'.PHP_EOL;
$regex = '/'.'"(?:\\\"|[^"])*"'.'/mi';
preg_match_all($regex,$contents,$matches);
foreach ($matches[0] as $match) {
if ($match == '""' || $match == '" "') {
continue;
}
echo "\t".'Deobfuscating: '.$match.PHP_EOL;
echo "\t\t".'New string: '.decrypt($match).PHP_EOL;
$contents = str_replace($encrypt_function.'('.$match.')',decrypt($match),$contents);
}
file_put_contents($file,$contents);
echo '}'.PHP_EOL;
}
function obfuscate($file) {
global $encrypt_function;
$contents = file_get_contents($file);
if (strpos($contents,$encrypt_function) !== false) {
echo 'File '.$file.' is already obfuscated'.PHP_EOL;
return;
}
echo 'Obfuscating file '.$file.' {'.PHP_EOL;
$regex = '/'.'"(?:\\\"|[^"])*"'.'/mi';
preg_match_all($regex,$contents,$matches);
foreach ($matches[0] as $match) {
if ($match == '""' || $match == '" "') {
continue;
}
echo "\t".'Obfuscating: '.$match.PHP_EOL;
echo "\t\t".'New string: '.$encrypt_function.'('.encrypt($match).')'.PHP_EOL;
$contents = str_replace($match,$encrypt_function.'('.encrypt($match).')',$contents);
}
$contents = str_replace('','',$contents);
file_put_contents($file,$contents);
echo '}'.PHP_EOL;
}
$di = new RecursiveDirectoryIterator('./');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
$filename = substr($filename,2);
$flag = false;
if (strpos($filename,'.java') === false) {
continue;
}
foreach (explode(',',$packages) as $package) {
if (strpos($package,',') !== false) {
$package = substr($package,1);
}
if (preg_match('/'.$package.'/im',$filename)) {
$flag = true;
break;
}
}
if ($flag == false) {
continue;
}
obfuscate($filename);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment