Showing posts with label reverse. Show all posts
Showing posts with label reverse. Show all posts

Monday, January 28, 2019

ClassModifier : Utility to easily modify your Java class files

Modify your Java class files easy with an interactive GUI.

Since it is not possible to edit a class file directly, this tool changes the class file to Smali version which is editable. After making the required changes, this tool converts the modified Smali to the modified Class file.
Features:
  • Modify a given Java class file
  • Allows Pen-tester to verify if their java desktop application is safe from Auth bypass
  • Can help you change the logical behavior of a Jar file by modifying a class
  • You can override private methods, change access modifier for variables of a class using ClassModifier.
  • Many other possibilities....

Download ClassModifier:



How to Use:

java -jar ClassModifier.jar

Menu:

File
  1. Open class (CTRL+O)- Takes the input class which need to be modified
  2. Open Project (CTRL+P)– You can reopen the project created using this feature.
  3. Save & Convert (CTRL+S) – Saves & Convert the code to modified Class and Smali file
  4. Export Class (CTRL+E) – Export modified class
  5. Java 2 Smali Helper - Opens a tab where you can write any Java code which on saving will show its equivalent Smali code
  6. Smali 2 Java code - Opens a tab where you can write any Smali code which on saving will show its equivalent Java code
Edit
  1. Increase Code FontSize (CTRL+I) – Allows you to increase font size of shown code.
  2. Decrease Code FontSize (CTRL+D) – Allows you to decrease the font size of shown code.
  3. Remove all tabs – Removes all currently shown tabs.
Decompiler
  1. Change Decompiler – Allows you to switch between jadx and jd-cli decompilers.

Help
  1. Update Software – Helps you to update the current software if any update is available
  2. How to use Class Modifier– Contains the documentation of this tool

Toolbar
  1. Allows you to find in current code/replace/replaceAll/find all class

ClassModifier_lib Folder

  1. It comes along with the software
  2. Contains the helper jars used by program
  3. ClassModifier_lib\userLibrary is automatically added in classpath while compiling code. If you wish to compile your code using external jars then place those external jars inside ClassModifier_lib\userLibrary

How to Use:
  • Open the Java class to be Modified
  • On opening, ClassModifier will open the Smali version of the class file
  • Edit the smali file and make the required changes
  • Save the smali file 
  • Modified java class file will be created which can be anytime exported using the File -> Export Class button.
  • Since Smali editing can be difficult, 2 options are provided - Java 2 Smali Helper and vice-versa.
  • As name suggests, Java 2 Smali Helper lets you see the Smali equivalent code for the input Java code.
  • Similarly, Smali 2 Java Helper lets you see the Java equivalent code for the input Smali code.

Screenshot:




Note: This software is meant for educational purpose only. Don't use it for any illegal activity.

Tuesday, April 4, 2017

Java Reflection- Accessing/Modifying private methods/fields

In this post we would access and modify private methods and fields from a class using Java Reflection. This operation wont be possible normally with Java.

Language Used:
Java

Focus Area:
  1. Access a method from a class having private constructor.
  2. Access a private method
  3. Access/Modify a private variable
Git Repo:
https://github.com/csanuragjain/extra/tree/master/ReflectionAccessModifyPrivateData

Related:
https://cooltrickshome.blogspot.in/2017/02/java-reflection-reading-unknown-class.html

Program:

Unknown2.java:
 package com.cooltrickshome;  
 public class Unknown2 {  
      private final String msg="This is final string from private variable";  
      private Unknown2(){  
      }  
      private String privateWelcome(String message)  
      {  
           message=message+" processed by private method";  
           return message;  
      }  
      public void showMessage(){  
           System.out.println("I should not be called since this class constructor is private");  
      }  
 }  

Explanation:
  1. This class has a private variable which is also final. So any other class should not ideally be able to access or modify it.
  2. The constructor of this class is private so you should not be able to create an instance of this class. Because of this we should not be able to call showMessage function.
  3. Method privateWelcome is private so another class should not be able to call this method.

AccessPrivateData.java
 package com.cooltrickshome;  
 import java.lang.reflect.Constructor;  
 import java.lang.reflect.Field;  
 import java.lang.reflect.Method;  
 public class AccessPrivateData {  
      public static void main(String[] args) throws Exception {  
           Class c=Class.forName("com.cooltrickshome.Unknown2");  
           //Class<Unknown2> c=Unknown2.class;  
           Constructor<Unknown2> constr=c.getDeclaredConstructor();  
           constr.setAccessible(true);  
           Unknown2 s=(Unknown2)constr.newInstance();   
           System.out.println("Calling method from class with private constructor:");  
           s.showMessage();   
           System.out.println();  
           Field field = c.getDeclaredField("msg");  
           field.setAccessible(true);  
           System.out.println("Calling private field:");  
           System.out.println(field.get(s));  
           System.out.println();  
           System.out.println("Changing a final variable value:");  
           field.set(s, "I have change a private final variable");  
           System.out.println(field.get(s));  
           System.out.println();  
           Method m= c.getDeclaredMethod("privateWelcome", String.class);  
           m.setAccessible(true);  
           Object o=m.invoke(s, "Calling private method");  
           System.out.println("Calling private method:");  
           System.out.println(o);  
      }  
 }  

Explanation:
  1. We will bypass all the constraint and access all the private data from Unknown2 class
  2. First we reference our Unknown2 class by using Class.forName passing the class to be accessed along with package name.
  3. Now we obtain the constructor of Unknown2 class by callling the getDeclaredConstructor method
  4. Since this contructor is private, so we remove the constraint by setting setAccessible as true
  5. Now we can create a new instance using newInstance method.
  6. Since an instance is ready so we can simply call the showMessage method
  7. Now lets access the private variable
  8. We obtain the private variable of Unknown2 class by calling getDeclaredField passing the field name.
  9. We call setAccessible to true on this field so that we can access this field even though it is private.
  10. Now we can retrieve this field value by simply calling get method passing the class instance object.
  11. Now lets change the final field value.
  12. Since this field setAccessible is already set to true earlier, we simply call the set method passing the Unknown2 class object and the new field value.
  13. Now lets access the private method.
  14. We obtain the private method by calling the getDeclaredMethod passing the private method name nd the type of argument it accepts (in our case the method needs a String)
  15. We call setAccessible to true on this method so that we can access this method even though it is private.
  16. We call the method by using invoke method, passing an instance of this class and the argument value.


Output:
 Calling method from class with private constructor:  
 I should not be called since this class constructor is private  
 Calling private field:  
 This is final string from private variable  
 Changing a final variable value:  
 I have change a private final variable  
 Calling private method:  
 Calling private method processed by private method  


Hope it helps :)

Thursday, March 30, 2017

APKRepatcher - Now Decompile & Recompile APK with easy GUI

APKRepatcher helps you to modify an existing apk using a simple user friendly GUI. It lets you edit java/smali code from an APK and rewrite the changes back to the modified signed APK. Additionally, it provides you option to convert Dex, Jar, Class, Smali, Class from one format to another. APKRepatcher makes use of dex2jar, jadx, rsyantaxtextarea, zip4j, apktool

Features:
  1. Decompiles/Recompiles the APK.
  2. Provides an editor to change the decompiled java code.
  3. Compiles the code using javac and saves the updated class.
  4. Allows you to view smali version of your modified java code.
  5. Allows you to edit smali from the original apk or from your modified java code
  6. Smali changes once saved would be reflected back in updated apk after building project.
  7. Build features re-creates new apk with all code changes and lastly it would resign the apk.
  8. Basic features like find/replace/increase or decrease font are also provided.
  9. It also allows you to convert from Dex to Jar/Class/Smali/Java, Jar to Dex/Java, Class to Dex/Smali, Smali to Class/Java/Dex. Also allows to extract and sign any apk.
  10. Allows you to change the amount of memory utilized by APKRepatcher.
  11. Patch Module
  12. APKRepatcher is created using Java with no os dependency (as far as i think) so you can run it with various OS
  13. 100% Free
How to run:
 java -jar APKRepatcher.jar  

File
  1. Open apk (CTRL+O)- Takes the input apk which need to be modified and extracts it inside <APKRepatcher_Software_Dir>/Projects/<APK_NAME_FOLDER>/
  2. Open Project (CTRL+P)– You can reopen the project created from open apk anytime using this feature. Just point it to <APK_NAME_FOLDER> inside Projects directory.
  3. Compile & Save (CTRL+S) – Saves & Compile the java code which is currently shown on the GUI editor.
  4. Build APK (CTRL+B) – Recreates a newly signed apk with the changed code.
Edit
  1. Increase Code FontSize (CTRL+I) – Allows you to increase font size of shown code.
  2. Decrease Code FontSize (CTRL+D) – Allows you to decrease the font size of shown code.
  3. Remove all tabs – Removes all currently shown tabs.
Extra
  1. Extract APK-APKTool – User can provide any apk for extraction using this option
  2. Convert Dex to Jar – User can convert any of dex file to jar format using this option
  3. Convert Dex to Class – User can convert any of dex file to class file using this option
  4. Convert Jar/Class to Dex – User can convert any of jar/class file to dex format using this option
  5. Convert Class to Smali – User can convert any of class file to smali format using this option
  6. Convert Smali to Class – User can convert any of smali file to class format using this option
  7. Convert Smali to Java – User can convert any of smali file to java format using this option
  8. Convert Dex to Smali – User can convert any of dex file to smali format using this option
  9. Convert Smali to Dex – User can convert any of smali file to dex format using this option
  10. Convert Dex/Jar to Java – User can convert any of dex/jar file to java format using this option
  11. Sign your apk – User can resign any apk using this option

Advanced
  1. Edit Smali using current code – Rewrite the smali version of the currently visible java code. This features requires the java code to be compilable in order to convert to smali.
  2. Edit Smali using original APK – This features opens the smali version of the java class from the original apk. Since it is extracted from original apk so no need of current java code to be compilable
  3. Save and apply smali changes – After you have edited smali code, you need to save it so that it gets reflected in modified apk.

Settings
  1. Change Memory Allocation – User is allowed to change the amount of memory reserved by APKRepatcher. Default is 1500mb or 1.5 GB

Help
  1. Update Software – Helps you to update the current software if any update is available
  2. How to use APKRepatcher – Contains the documentation of APKRepatcher.

Toolbar
  1. Allows you to find in current code/replace/replaceAll/find all class


Extra Software Content:

APKRepatcher_lib Folder
  1. It comes along with the software
  2. Contains the helper jars used by program
  3. APKRepatcher_lib\userLibrary is automatically added in classpath while compiling code. If you wish to compile your code using external jars then place those external jars inside APKRepatcher_lib\userLibrary

Settings.txt File
  1. Contains the memory utilized by APKRepatcher.

Software Screenshot:


Things to Remember:
  1. The default memory allocated to APKRepatcher is 1500mb which can be changed simply using Settings -> Change Memory Allocation
  2. You can add external library while compiling your code by simply placing them under APKRepatcher_lib\userLibrary folder
  3. You can also use APKRepatcher for converting dex/jar/class/smali/java from one format to another.
  4. Patch a module - Assume a class is non compilable because of certain modules used, but you wish to change one of methods which does not have any issue. In this case you can remove the non compilable methods, keeping only your changed method. Now select edit smali for current code under Advanced. You will obtain the smali version for your java module. Now choose Advanced -> edit smali using original apk. Replace your modified module in the original apk smali and then click on Advanced -> save and apply changes. When you build the project, it would patch the module. So you are saved from the errors :)
  5. You can always increase or decrease the font size of the code using hotkeys or from Edit section
  6. Don't forget to build the apk after you made your changes. It will create the new apk.
  7. All projects are stored in the Projects directory which comes along with the software.
Tutorial:
  1. Open APKRepatcher using java -jar APKRepatcher.jar
  2. Click on File -> Open APK
  3. Choose the apk you wish to change
  4. Open the package from the left pane and double click on the java file you want to edit.
  5. Once java file opens in editor, just make the required changes.
  6. After you made the changes, click on File -> Compile & Save
  7. If compilation fails, you will see the errors in the console view.
  8. Fix them and compile again
  9. Once compilation succeeds, you click on File -> Build APK
  10. If build succeeds, you would see the new apk created.
  11. If you are unable to compile your class, and want to make changes directly to smali then you can click on Advanced -> edit smali using original apk (which will open the current code smali from the original apk) and make the edits and then click on Advanced -> save and apply. After that you can click on File -> Build APK
  12. Assume a class is non compilable because of certain modules used, but you wish to change one of methods which does not have any issue. In this case you can remove the non compilable methods, keeping only your changed method. Now select edit smali for current code under Advanced. You will obtain the smali version for your java module. Now choose Advanced -> edit smali using original apk. Replace your modified module in the original apk smali and then click on Advanced -> save and apply changes. When you build the project, it would patch the module. So you are saved from the errors
Note: This software is meant for educational purpose only. Don't use it for any illegal activity.

Sunday, February 26, 2017

Java Reflection- Reading unknown class file

Java Reflection allows you to inspect interfaces, fields and methods from a known or an unknown class. It also allows you to call methods from these unknown class which otherwise wont be possible.
This post is for inspecting class , methods, constructors, fields from an unknown class. In the next post, I would be sharing on how you could utilize and execute those retrieved methods.

Reference:
http://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful
http://www.javatpoint.com/java-reflection
http://tutorials.jenkov.com/java-reflection/index.html
http://www.oracle.com/technetwork/articles/java/javareflection-1536171.html

Language Used:
Java

Git Location:
https://github.com/csanuragjain/extra/tree/master/ReflectionReadAPI

Related:
https://cooltrickshome.blogspot.in/2017/04/java-reflection-accessingmodifying.html

Pre-requisite:

1) We have a class file named Unknown.class.
2) Unknown.class is the compiled class file and contains the byte code
3) You cannot check the methods and fields from this class unless you deobfuscate the java file
4) You cannot directly call the methods from this class in Eclipse unless and until you copy the java source code which you obtained by deobfuscating this class into a new java file in eclipse. (Or you use Reflection, which we will see :) )

Program:

Obtaining the real class name from Unknown.class:
      public static void main(String[] args) {  
           ClassLoader cl;  
           Class c;  
           try {  
           File file = new File(".");  
           URL url = file.toURL();  
        URL[] urls = new URL[]{url};  
        cl = new URLClassLoader(urls);  
        c = cl.loadClass("Unknown");  
        System.out.println(c.isInterface());   
           } catch (ClassNotFoundException e) {  
                System.out.println("Requested class was not found "+e.getMessage());  
           } catch (MalformedURLException e) {  
                System.out.println("Given class file url was not found "+e.getMessage());  
           }  
      }  

Output:

How it works:
1) We place the Unknown.class in the current project directory.
2) We make a File object which points to the directory where Unknown.class is present. Since it is present in current directory we keep path as '.'
3) We make a URL object using the above File object and then pass this object in a URL array.
4) We use URLClassLoader to load the class from the URL we created.
5) We retrieve the class instance using loadClass
6) isInterface method tells if Unknown.class is an interface
7) When we run this class we get an error wrong name: com/cooltrickshome/completed/RunExternalProgram
8) This tells that real name of Unknown.class is RunExternalProgram.class and its part of package com.cooltrickshome.completed.RunExternalProgram
9) After knowing this, we create folders com/cooltrickshome/completed inside the current project directory (why: refer step 2)
10) We rename Unknown.class to RunExternalProgram.class and place it inside com/cooltrickshome/completed folder
11) Finally we change loadClass to cl.loadClass("com.cooltrickshome.completed.RunExternalProgram");
12) Folder structure finally becomes ./com/cooltrickshome/completed/RunExternalProgram.class

Obtaining the method name from this class file:
      public void printMethods(Class c) {  
           // Getting all the methods  
           System.out.println("\nMethods of this class");  
           Method methlist[] = c.getDeclaredMethods();  
           for (int i = 0; i < methlist.length; i++) {  
                Method m = methlist[i];  
                System.out.println(m.toString());  
                System.out.println("Method Name: " + m.getName());  
                System.out.println("Declaring Class: " + m.getDeclaringClass());  
                Class param[] = m.getParameterTypes();  
                for (int j = 0; j < param.length; j++)  
                     System.out.println("Param #" + j + ": " + param[j]);  
                Class exec[] = m.getExceptionTypes();  
                for (int j = 0; j < exec.length; j++)  
                     System.out.println("Exception thrown by method #" + j + ": "  
                               + exec[j]);  
                System.out.println("Method Return type: " + m.getReturnType());  
                System.out  
                          .println("--------------------------------------------------\n");  
           }  
      }  

Output:
 Methods of this class  
 public static void com.cooltrickshome.completed.RunExternalProgram.main(java.lang.String[]) throws java.lang.InterruptedException,java.io.IOException  
 Method Name: main  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: class [Ljava.lang.String;  
 Exception thrown by method #0: class java.lang.InterruptedException  
 Exception thrown by method #1: class java.io.IOException  
 Method Return type: void  
 --------------------------------------------------  
 public int com.cooltrickshome.completed.RunExternalProgram.getCounter(int)  
 Method Name: getCounter  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: int  
 Method Return type: int  
 --------------------------------------------------  
 public void com.cooltrickshome.completed.RunExternalProgram.runProgram(java.lang.String[]) throws java.lang.InterruptedException,java.io.IOException  
 Method Name: runProgram  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: class [Ljava.lang.String;  
 Exception thrown by method #0: class java.lang.InterruptedException  
 Exception thrown by method #1: class java.io.IOException  
 Method Return type: void  
 --------------------------------------------------  
 public void com.cooltrickshome.completed.RunExternalProgram.incrementCounter(int)  
 Method Name: incrementCounter  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: int  
 Method Return type: void  
 --------------------------------------------------  

How it works:
1) getDeclaredMethods is used to retrieve the methods from the class passed in argument
2) We iterate through each method in a for loop
3) toString method of this method will print the full function prototype
4) getName is used to print the method name
5) getDeclaringClass is used to print the declaring class
6) getParameterTypes is used to retrieve the parameters type used by this method
7) getExceptionTypes is used to find the exception which this method throws
8) getReturnType is used to retrieve the return type of this method.

Obtaining the Constructors from the class file:
      public void printConstructor(Class c) {  
           // Getting all the constructor  
           System.out.println("Constructor of this class");  
           Constructor[] constlist = c.getDeclaredConstructors();  
           for (int i = 0; i < constlist.length; i++) {  
                Constructor m = constlist[i];  
                System.out.println(m.toString());  
                System.out.println("Method Name: " + m.getName());  
                System.out.println("Declaring Class: " + m.getDeclaringClass());  
                Class param[] = m.getParameterTypes();  
                for (int j = 0; j < param.length; j++)  
                     System.out.println("Param #" + j + ": " + param[j]);  
                Class exec[] = m.getExceptionTypes();  
                for (int j = 0; j < exec.length; j++)  
                     System.out.println("Exception thrown by method #" + j + ": "  
                               + exec[j]);  
                System.out  
                          .println("--------------------------------------------------\n");  
           }  
      }  

Output:
 Constructor of this class  
 public com.cooltrickshome.completed.RunExternalProgram()  
 Method Name: com.cooltrickshome.completed.RunExternalProgram  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 --------------------------------------------------  
 public com.cooltrickshome.completed.RunExternalProgram(int)  
 Method Name: com.cooltrickshome.completed.RunExternalProgram  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: int  
 --------------------------------------------------  

How it works:
1) getDeclaredConstructors is used to retrieve the constructors from the class passed in argument
2) We iterate through each constructor in a for loop
3) toString method will print the full constructor prototype
4) getName is used to print the constructor name
5) getDeclaringClass is used to print the declaring class
6) getParameterTypes is used to retrieve the parameters type used by this constructor 
7) getExceptionTypes is used to find the exception which this constructor throws

Obtaining the variables from the class file:
 public void printFields(Class c)  
      {  System.out.println("Variables of this class");
           Field fieldlist[]   
             = c.getDeclaredFields();  
            for (int i   
             = 0; i < fieldlist.length; i++) {  
              Field fld = fieldlist[i];  
              System.out.println("Variable name: " + fld.getName());  
              System.out.println("Declaring class: " +fld.getDeclaringClass());  
              System.out.println("Variable type: " + fld.getType());  
              int mod = fld.getModifiers();  
              System.out.println("Modifiers = " +Modifier.toString(mod));  
              System.out.println("--------------------------------");  
            }  
      }  

Output:
 Variables of this class  
 Variable name: counter  
 Declaring class: class com.cooltrickshome.completed.RunExternalProgram  
 Variable type: int  
 Modifiers = private  
 --------------------------------------------------  

How it works:
1) getDeclaredFields is used to retrieve the variables from the class passed in argument
2) We iterate through each variable in a for loop
3) getName is used to print the variable name
4) getDeclaringClass is used to print the declaring class
5) getParameterTypes is used to retrieve the variable type used by this variable 
7) getModifiers() retrieve the modifier of this variable.

Full Program : (Available from git location)

RunExternalProgram.class:
Placed at <current project directory>/cooltrickshome/completed/RunExternalProgram.class

ReflectionReadApi.java:
 package com.cooltrickshome;  
 import java.io.File;  
 import java.lang.reflect.Constructor;  
 import java.lang.reflect.Field;  
 import java.lang.reflect.Method;  
 import java.lang.reflect.Modifier;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.net.URLClassLoader;  
 public class ReflectionReadApi {  
      /**  
       * @param args  
       * @throws ClassNotFoundException  
       */  
      public static void main(String[] args) {  
           ClassLoader cl;  
           Class c;  
           try {  
                File file = new File(".");  
                URL url = file.toURL();  
                URL[] urls = new URL[] { url };  
                cl = new URLClassLoader(urls);  
                c = cl.loadClass("com.cooltrickshome.completed.RunExternalProgram");  
                System.out.println("\nName of class is " + c.getName());  
                ReflectionReadApi ra = new ReflectionReadApi();  
                ra.printMethods(c);  
                ra.printConstructor(c);  
                ra.printFields(c);  
           } catch (ClassNotFoundException e) {  
                System.out.println("Requested class was not found "  
                          + e.getMessage());  
           } catch (MalformedURLException e) {  
                System.out.println("Given class file url was not found "  
                          + e.getMessage());  
           }  
      }  
      public void printMethods(Class c) {  
           // Getting all the methods  
           System.out.println("\nMethods of this class");  
           Method methlist[] = c.getDeclaredMethods();  
           for (int i = 0; i < methlist.length; i++) {  
                Method m = methlist[i];  
                System.out.println(m.toString());  
                System.out.println("Method Name: " + m.getName());  
                System.out.println("Declaring Class: " + m.getDeclaringClass());  
                Class param[] = m.getParameterTypes();  
                for (int j = 0; j < param.length; j++)  
                     System.out.println("Param #" + j + ": " + param[j]);  
                Class exec[] = m.getExceptionTypes();  
                for (int j = 0; j < exec.length; j++)  
                     System.out.println("Exception thrown by method #" + j + ": "  
                               + exec[j]);  
                System.out.println("Method Return type: " + m.getReturnType());  
                System.out  
                          .println("--------------------------------------------------\n");  
           }  
      }  
      public void printConstructor(Class c) {  
           // Getting all the constructor  
           System.out.println("Constructor of this class");  
           Constructor[] constlist = c.getDeclaredConstructors();  
           for (int i = 0; i < constlist.length; i++) {  
                Constructor m = constlist[i];  
                System.out.println(m.toString());  
                System.out.println("Method Name: " + m.getName());  
                System.out.println("Declaring Class: " + m.getDeclaringClass());  
                Class param[] = m.getParameterTypes();  
                for (int j = 0; j < param.length; j++)  
                     System.out.println("Param #" + j + ": " + param[j]);  
                Class exec[] = m.getExceptionTypes();  
                for (int j = 0; j < exec.length; j++)  
                     System.out.println("Exception thrown by method #" + j + ": "  
                               + exec[j]);  
                System.out  
                          .println("--------------------------------------------------\n");  
           }  
      }  
      public void printFields(Class c)  
      {  
           System.out.println("Variables of this class");  
           Field fieldlist[]   
             = c.getDeclaredFields();  
            for (int i   
             = 0; i < fieldlist.length; i++) {  
              Field fld = fieldlist[i];  
              System.out.println("Variable name: " + fld.getName());  
              System.out.println("Declaring class: " +fld.getDeclaringClass());  
              System.out.println("Variable type: " + fld.getType());  
              int mod = fld.getModifiers();  
              System.out.println("Modifiers = " +Modifier.toString(mod));  
              System.out.println("--------------------------------------------------\n");  
            }  
      }  
 }  

Output:
 Name of class is com.cooltrickshome.completed.RunExternalProgram  
 Methods of this class  
 public static void com.cooltrickshome.completed.RunExternalProgram.main(java.lang.String[]) throws java.lang.InterruptedException,java.io.IOException  
 Method Name: main  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: class [Ljava.lang.String;  
 Exception thrown by method #0: class java.lang.InterruptedException  
 Exception thrown by method #1: class java.io.IOException  
 Method Return type: void  
 --------------------------------------------------  
 public void com.cooltrickshome.completed.RunExternalProgram.runProgram(java.lang.String[]) throws java.lang.InterruptedException,java.io.IOException  
 Method Name: runProgram  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: class [Ljava.lang.String;  
 Exception thrown by method #0: class java.lang.InterruptedException  
 Exception thrown by method #1: class java.io.IOException  
 Method Return type: void  
 --------------------------------------------------  
 public int com.cooltrickshome.completed.RunExternalProgram.getCounter(int)  
 Method Name: getCounter  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: int  
 Method Return type: int  
 --------------------------------------------------  
 public void com.cooltrickshome.completed.RunExternalProgram.incrementCounter(int)  
 Method Name: incrementCounter  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: int  
 Method Return type: void  
 --------------------------------------------------  
 Constructor of this class  
 public com.cooltrickshome.completed.RunExternalProgram()  
 Method Name: com.cooltrickshome.completed.RunExternalProgram  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 --------------------------------------------------  
 public com.cooltrickshome.completed.RunExternalProgram(int)  
 Method Name: com.cooltrickshome.completed.RunExternalProgram  
 Declaring Class: class com.cooltrickshome.completed.RunExternalProgram  
 Param #0: int  
 --------------------------------------------------  
 Variables of this class  
 Variable name: counter  
 Declaring class: class com.cooltrickshome.completed.RunExternalProgram  
 Variable type: int  
 Modifiers = private  
 --------------------------------------------------  


Hope it helps :)

Sunday, December 4, 2016

Search inside your images using Java

This software will let you search any person or thing from your album,wallpaper,or even from internet websites like facebook.
Our Java program automates the Google Image search so that the image search becomes very simple.

Language Used:
Java/C++

Git Repo:
https://github.com/csanuragjain/extra/tree/master/ImageResolver

Full Software:
https://github.com/csanuragjain/extra/blob/master/ImageResolver/Software/ImageResolver.jar?raw=true
https://github.com/csanuragjain/extra/blob/master/ImageResolver/Software/ImageResolver.dll?raw=true

Pre-requisite:
Download url:
ImagePanel.java :    
https://github.com/csanuragjain/recorder/blob/master/DesktopScreenshotMaker/Code/ImagePanel.java  
MyLogger.dll :    
https://github.com/csanuragjain/recorder/blob/master/DesktopScreenshotMaker/Code/dll/MyLogger.dll  

References:
https://cooltrickshome.blogspot.in/2016/11/create-desktop-screenshot-maker.html https://cooltrickshome.blogspot.in/2016/11/creating-your-personal-keylogger-from.html

POM Dependency:
 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->  
 <dependency>  
   <groupId>org.apache.httpcomponents</groupId>  
   <artifactId>httpclient</artifactId>  
   <version>4.5.2</version>  
 </dependency>  
 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->  
 <dependency>  
   <groupId>org.apache.httpcomponents</groupId>  
   <artifactId>httpmime</artifactId>  
   <version>4.5.2</version>  
 </dependency>  

How it works:

1) Suppose you see an actor on an image on your facebook posts
2) Just Press F8
3) Use your mouse and drag that actor image using mouse
4) Software will upload that actor image to Google and show you the result instantly.
5) For exiting the software simply press F9

Note:
1) As mentioned on pressing F8 a separate frame open up with user current screen background for selecting the image region. In some cases the open frame may get minimized so in those case user will need to maximize the window and then select the region.

Major Module:

Upload method:
  public void upload(File file)  
   throws Exception  
  {  
   final JFrame temp = new JFrame("Searching...");  
   Thread t2 = new Thread()  
   {  
    public void run()  
    {  
     temp.setSize(250, 0);  
     temp.setLayout(new FlowLayout());  
     temp.setVisible(true);  
     temp.setDefaultCloseOperation(2);  
    }  
   };  
   t2.start();  
   MultipartEntity entity = new MultipartEntity();  
   entity.addPart("encoded_image", new InputStreamBody(new FileInputStream(file), file.getName()));  
   HttpPost post = new HttpPost("https://www.google.com/searchbyimage/upload");  
   post.setEntity(entity);  
   HttpClient client = new DefaultHttpClient();  
   HttpResponse response = client.execute(post);  
   String site = response.getFirstHeader("location").getValue();  
   Runtime.getRuntime().exec("cmd /c start " + site);  
   temp.dispose();  
   lock = false;  
  }  

How it works:
1) This module receives the file object pointing to the screenshot of the image to be searched
2) We show a frame to user saying Searching
3) Now we make a POST call to https://www.google.com/searchbyimage/upload and pass the file object we received as argument.
4) The response from google contains the page having result in the location header. We fetch the url from location header.
5) We use runtime to open the url found in previous step
6) The http library dependency are mentioned in POM Dependency section of this blog post.

showFrame method:
  public void showFrame()  
   throws Exception  
  {  
   lock = true;  
   Dimension size = Toolkit.getDefaultToolkit().getScreenSize();  
   Robot robot = new Robot();  
   BufferedImage img = robot.createScreenCapture(new Rectangle(size));  
   ImagePanel panel = new ImagePanel(img);  
   add(panel);  
   setLocation(0, 0);  
   setSize(size);  
   setLayout(new FlowLayout());  
   setUndecorated(true);  
   setVisible(true);  
   addMouseListener(this);  
   addMouseMotionListener(this);  
   setDefaultCloseOperation(2);  
  }  

How it works:
1) When a user press F8 this module is used
2) It takes screenshot of the current user screen and paste that on a JFrame
3) JFrame having the screen background is shown to user where now user can use his mouse to drag the portion of image which he would like to search.
4) This module use ImagePanel which you can get from Pre-requisite section of this blog post.

main Method:

  public static void main(String[] args)  
  {  
   try  
   {  
    JFrame f1 = new JFrame("ImageResolver Help (Exit the App using F9)");  
    JLabel l1 = new JLabel("Please read this before continuing to the program");  
    JLabel l2 = new JLabel("Begin Image Search");  
    JLabel l3 = new JLabel("To begin Image Search,Open the image and then press F8 key");  
    JLabel l4 = new JLabel("A window will open.Just drag the area of the image which you want to search");  
    JLabel l5 = new JLabel("After a small delay the search results will be displayed");  
    JLabel l6 = new JLabel("------------------------------------------------------------------");  
    JLabel l7 = new JLabel("Exit the program");  
    JLabel l8 = new JLabel("For exiting the program Press F9.A confirmation message will be displayed and after that application will close.");  
    JLabel l9 = new JLabel("------------------------------------------------------------------");  
    JLabel l10 = new JLabel("Note: Multiple Searches are not allowed. Please close this window before staring to use the software.");  
    JLabel blank = new JLabel("");  
    JLabel startinfo7 = new JLabel("Software has been Developed by....");  
    JLabel startinfo8 = new JLabel("Anurag Jain");  
    JLabel startinfo9 = new JLabel("Software Engineer");  
    JLabel startinfo10 = new JLabel("(cs.anurag.jain@gmail.com)");  
    JLabel startinfo11 = new JLabel("Project Homepage: https://cooltrickshome.blogspot.in");  
    JLabel startinfo12 = new JLabel("For any problems or feedback you may contact me directly at cs.anurag.jain@gmail.com");  
    f1.add(l1);  
    f1.add(l2);  
    f1.add(l3);  
    f1.add(l4);  
    f1.add(l5);  
    f1.add(l6);  
    f1.add(l7);  
    f1.add(l8);  
    f1.add(l9);  
    f1.add(l10);  
    f1.add(blank);  
    f1.add(blank);  
    f1.add(blank);  
    f1.add(startinfo7);  
    f1.add(startinfo8);  
    f1.add(startinfo9);  
    f1.add(startinfo10);  
    f1.add(startinfo11);  
    f1.add(startinfo12);  
    f1.setLayout(new GridLayout(19, 1));  
    f1.setVisible(true);  
    f1.setSize(700, 700);  
    f1.setDefaultCloseOperation(2);  
    Thread t1 = new Thread(new ImageResolver());  
    t1.start();  
   }  
   catch (Exception e)  
   {  
    JOptionPane.showConfirmDialog(  
     null, "Some Problem Occured.Please try again", "Error",   
     -1);  
   }  
  }  

How it works:
1) We make a Jframe and show how software is going to work
2) We start the thread made in this class so the run method gets called

run Method:
  public synchronized void run()  
  {  
   for (;;)  
   {  
    int value = getKeys();  
    if ((value == 119) && (lock))  
    {  
     JOptionPane.showConfirmDialog(  
      null, "You can only run one query at a time.Let the previous search complete then you may continue with the new search", "Error",   
      -1);  
    }  
    else if ((value == 119) && (!lock))  
    {  
     try  
     {  
      Thread t2 = new Thread()  
      {  
       public void run()  
       {  
        try  
        {  
         new ImageResolver().showFrame();  
        }  
        catch (Exception e)  
        {  
         ImageResolver.lock = false;  
         JOptionPane.showConfirmDialog(  
          null, "Some Problem Occured.Please try again", "Error",   
          -1);  
        }  
       }  
      };  
      t2.start();  
     }  
     catch (Exception e)  
     {  
      lock = false;  
      JOptionPane.showConfirmDialog(  
          null, "Some Problem Occured.Please try again", "Error",   
          -1);  
     }  
    }  
    else if (value == 120)  
    {  
     JOptionPane.showConfirmDialog(  
      null, "Exiting...", "Exit",   
      -1);  
     System.exit(0);  
    }  
   }  
  }  

How it works:
1) This thread keep track of the key pressed by user. It makes use of ImageResolver.dll which you can obtain from pre-requisite section of this blog post.
2) 119 is keycode of F8 and 120 is keycode for F9 as already told in earlier post for keylogger (References section)
3) lock variable make sure that user can perform only one search at a time
4) If user press F8 then showFrame method gets called
5) If user press F9 then program exits

Mouse events method:
  public void draggedScreen()  
   throws Exception  
  {  
   int w = this.c1 - this.c3;  
   int h = this.c2 - this.c4;  
   w *= -1;  
   h *= -1;  
   Robot robot = new Robot();  
   BufferedImage img = robot.createScreenCapture(new Rectangle(this.c1, this.c2, w, h));  
   File save_path = new File("screen1.jpg");  
   ImageIO.write(img, "JPG", save_path);  
   dispose();  
   upload(save_path);  
  }  
   public void mouseClicked(MouseEvent arg0) {}  
  public void mouseEntered(MouseEvent arg0) {}  
  public void mouseExited(MouseEvent arg0) {}  
  public void mousePressed(MouseEvent arg0)  
  {  
   repaint();  
   this.c1 = arg0.getX();  
   this.c2 = arg0.getY();  
  }  
  public void mouseReleased(MouseEvent arg0)  
  {  
   repaint();  
   if (this.drag_status == 1)  
   {  
    this.c3 = arg0.getX();  
    this.c4 = arg0.getY();  
    try  
    {  
     draggedScreen();  
    }  
    catch (Exception e)  
    {  
     e.printStackTrace();  
    }  
   }  
  }  
  public void mouseDragged(MouseEvent arg0)  
  {  
   repaint();  
   this.drag_status = 1;  
   this.c3 = arg0.getX();  
   this.c4 = arg0.getY();  
  }  
  public void mouseMoved(MouseEvent arg0) {}  
  public void paint(Graphics g)  
  {  
   super.paint(g);  
   int w = this.c1 - this.c3;  
   int h = this.c2 - this.c4;  
   w *= -1;  
   h *= -1;  
   if (w < 0) {  
    w *= -1;  
   }  
   g.drawRect(this.c1, this.c2, w, h);  
  }  


How it works:
1) When mouse is pressed we record the starting coordinate in c1 & c2
2) When mouse is dragged then we record the ending coordinate in c3 & c4. We call the paint method which starts drawing the rectangle to show the selected region described by (c1,c2) & (c3,c4)
3) When mouse is released we get the final region for which screenshot need to taken and update c3 and c4.

4) We call draggedScreen method which simply takes the screenshot of the region selected by user and saves it using ImageIO write method.
5) Finally upload method gets called which retreives the result for this image.

Output:





Full Program:

ImageResolver.java
 package com.cooltrickshome;  
 import java.awt.Dimension;  
 import java.awt.FlowLayout;  
 import java.awt.Graphics;  
 import java.awt.GridLayout;  
 import java.awt.Rectangle;  
 import java.awt.Robot;  
 import java.awt.Toolkit;  
 import java.awt.event.MouseEvent;  
 import java.awt.event.MouseListener;  
 import java.awt.event.MouseMotionListener;  
 import java.awt.image.BufferedImage;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import javax.imageio.ImageIO;  
 import javax.swing.JFrame;  
 import javax.swing.JLabel;  
 import javax.swing.JOptionPane;  
 import org.apache.http.Header;  
 import org.apache.http.HttpResponse;  
 import org.apache.http.client.HttpClient;  
 import org.apache.http.client.methods.HttpPost;  
 import org.apache.http.entity.mime.MultipartEntity;  
 import org.apache.http.entity.mime.content.InputStreamBody;  
 import org.apache.http.impl.client.DefaultHttpClient;  
 public class ImageResolver  
  extends JFrame  
  implements MouseListener, MouseMotionListener, Runnable  
 {  
  int drag_status = 0;  
  int c1;  
  int c2;  
  int c3;  
  int c4;  
  static boolean lock = false;  
  static  
  {  
   System.loadLibrary("ImageResolver");  
  }  
  private native int getKeys();  
  public void showFrame()  
   throws Exception  
  {  
   lock = true;  
   Dimension size = Toolkit.getDefaultToolkit().getScreenSize();  
   Robot robot = new Robot();  
   BufferedImage img = robot.createScreenCapture(new Rectangle(size));  
   ImagePanel panel = new ImagePanel(img);  
   add(panel);  
   setLocation(0, 0);  
   setSize(size);  
   setLayout(new FlowLayout());  
   setUndecorated(true);  
   setVisible(true);  
   addMouseListener(this);  
   addMouseMotionListener(this);  
   setDefaultCloseOperation(2);  
  }  
  public void upload(File file)  
   throws Exception  
  {  
   final JFrame temp = new JFrame("Searching...");  
   Thread t2 = new Thread()  
   {  
    public void run()  
    {  
     temp.setSize(250, 0);  
     temp.setLayout(new FlowLayout());  
     temp.setVisible(true);  
     temp.setDefaultCloseOperation(2);  
    }  
   };  
   t2.start();  
   MultipartEntity entity = new MultipartEntity();  
   entity.addPart("encoded_image", new InputStreamBody(new FileInputStream(file), file.getName()));  
   HttpPost post = new HttpPost("https://www.google.com/searchbyimage/upload");  
   post.setEntity(entity);  
   HttpClient client = new DefaultHttpClient();  
   HttpResponse response = client.execute(post);  
   String site = response.getFirstHeader("location").getValue();  
   Runtime.getRuntime().exec("cmd /c start " + site);  
   temp.dispose();  
   lock = false;  
  }  
  public void draggedScreen()  
   throws Exception  
  {  
   int w = this.c1 - this.c3;  
   int h = this.c2 - this.c4;  
   w *= -1;  
   h *= -1;  
   Robot robot = new Robot();  
   BufferedImage img = robot.createScreenCapture(new Rectangle(this.c1, this.c2, w, h));  
   File save_path = new File("screen1.jpg");  
   ImageIO.write(img, "JPG", save_path);  
   dispose();  
   upload(save_path);  
  }  
  public synchronized void run()  
  {  
   for (;;)  
   {  
    int value = getKeys();  
    if ((value == 119) && (lock))  
    {  
     JOptionPane.showConfirmDialog(  
      null, "You can only run one query at a time.Let the previous search complete then you may continue with the new search", "Error",   
      -1);  
    }  
    else if ((value == 119) && (!lock))  
    {  
     try  
     {  
      Thread t2 = new Thread()  
      {  
       public void run()  
       {  
        try  
        {  
         new ImageResolver().showFrame();  
        }  
        catch (Exception e)  
        {  
         ImageResolver.lock = false;  
         JOptionPane.showConfirmDialog(  
          null, "Some Problem Occured.Please try again", "Error",   
          -1);  
        }  
       }  
      };  
      t2.start();  
     }  
     catch (Exception e)  
     {  
      lock = false;  
      JOptionPane.showConfirmDialog(  
          null, "Some Problem Occured.Please try again", "Error",   
          -1);  
     }  
    }  
    else if (value == 120)  
    {  
     JOptionPane.showConfirmDialog(  
      null, "Exiting...", "Exit",   
      -1);  
     System.exit(0);  
    }  
   }  
  }  
  public static void main(String[] args)  
  {  
   try  
   {  
    JFrame f1 = new JFrame("ImageResolver Help (Exit the App using F9)");  
    JLabel l1 = new JLabel("Please read this before continuing to the program");  
    JLabel l2 = new JLabel("Begin Image Search");  
    JLabel l3 = new JLabel("To begin Image Search,Open the image and then press F8 key");  
    JLabel l4 = new JLabel("A window will open.Just drag the area of the image which you want to search");  
    JLabel l5 = new JLabel("After a small delay the search results will be displayed");  
    JLabel l6 = new JLabel("------------------------------------------------------------------");  
    JLabel l7 = new JLabel("Exit the program");  
    JLabel l8 = new JLabel("For exiting the program Press F9.A confirmation message will be displayed and after that application will close.");  
    JLabel l9 = new JLabel("------------------------------------------------------------------");  
    JLabel l10 = new JLabel("Note: Multiple Searches are not allowed. Please close this window before staring to use the software.");  
    JLabel blank = new JLabel("");  
    JLabel startinfo7 = new JLabel("Software has been Developed by....");  
    JLabel startinfo8 = new JLabel("Anurag Jain");  
    JLabel startinfo9 = new JLabel("Software Engineer");  
    JLabel startinfo10 = new JLabel("(cs.anurag.jain@gmail.com)");  
    JLabel startinfo11 = new JLabel("Project Homepage: https://cooltrickshome.blogspot.in");  
    JLabel startinfo12 = new JLabel("For any problems or feedback you may contact me directly at cs.anurag.jain@gmail.com");  
    f1.add(l1);  
    f1.add(l2);  
    f1.add(l3);  
    f1.add(l4);  
    f1.add(l5);  
    f1.add(l6);  
    f1.add(l7);  
    f1.add(l8);  
    f1.add(l9);  
    f1.add(l10);  
    f1.add(blank);  
    f1.add(blank);  
    f1.add(blank);  
    f1.add(startinfo7);  
    f1.add(startinfo8);  
    f1.add(startinfo9);  
    f1.add(startinfo10);  
    f1.add(startinfo11);  
    f1.add(startinfo12);  
    f1.setLayout(new GridLayout(19, 1));  
    f1.setVisible(true);  
    f1.setSize(700, 700);  
    f1.setDefaultCloseOperation(2);  
    Thread t1 = new Thread(new ImageResolver());  
    t1.start();  
   }  
   catch (Exception e)  
   {  
    JOptionPane.showConfirmDialog(  
     null, "Some Problem Occured.Please try again", "Error",   
     -1);  
   }  
  }  
  public void mouseClicked(MouseEvent arg0) {}  
  public void mouseEntered(MouseEvent arg0) {}  
  public void mouseExited(MouseEvent arg0) {}  
  public void mousePressed(MouseEvent arg0)  
  {  
   repaint();  
   this.c1 = arg0.getX();  
   this.c2 = arg0.getY();  
  }  
  public void mouseReleased(MouseEvent arg0)  
  {  
   repaint();  
   if (this.drag_status == 1)  
   {  
    this.c3 = arg0.getX();  
    this.c4 = arg0.getY();  
    try  
    {  
     draggedScreen();  
    }  
    catch (Exception e)  
    {  
     e.printStackTrace();  
    }  
   }  
  }  
  public void mouseDragged(MouseEvent arg0)  
  {  
   repaint();  
   this.drag_status = 1;  
   this.c3 = arg0.getX();  
   this.c4 = arg0.getY();  
  }  
  public void mouseMoved(MouseEvent arg0) {}  
  public void paint(Graphics g)  
  {  
   super.paint(g);  
   int w = this.c1 - this.c3;  
   int h = this.c2 - this.c4;  
   w *= -1;  
   h *= -1;  
   if (w < 0) {  
    w *= -1;  
   }  
   g.drawRect(this.c1, this.c2, w, h);  
  }  
 }  

ImagePanel.java
 package com.cooltrickshome;  
 import java.awt.Dimension;  
 import java.awt.Graphics;  
 import java.awt.Image;  
 import javax.swing.ImageIcon;  
 import javax.swing.JPanel;  
 class ImagePanel  
  extends JPanel  
 {  
  private Image img;  
  public ImagePanel(String img)  
  {  
   this(new ImageIcon(img).getImage());  
  }  
  public ImagePanel(Image img)  
  {  
   this.img = img;  
   Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));  
   setPreferredSize(size);  
   setMinimumSize(size);  
   setMaximumSize(size);  
   setSize(size);  
   setLayout(null);  
  }  
  public void paintComponent(Graphics g)  
  {  
   g.drawImage(this.img, 0, 0, null);  
  }  
 }  

ImageResolver.dll
https://github.com/csanuragjain/extra/blob/master/ImageResolver/Software/ImageResolver.dll?raw=true

Hope it helps :)