Java encryption decrypts class file, using ClassLoader to dynamically decrypt class files

Source: Internet
Author: User
Tags decrypt

Objective

In the daily development, you may encounter to be sensitive to the system of code to protect, then the following summarizes the way to protect the source of the simplest way, that is, file encryption

First of all, the general idea of encryption and decryption is: encryption is nothing more than the class file is different or a bit, decryption, that is, the class file will be different or back.

Encrypted files if you want to use, you need to ClassLoader dynamic loading in, specific implementation please move to: Custom classloader dynamic load class file

Code implementation
1 /**2 * Add decryption class3  */4  Public classEdcipher {5 6     PrivateString Encryptfolder = "Encrypt";7 8     /**9 * Encryption MethodTen      * @paramName requires an encrypted file name One      */ A      Public voidEncryptclass (String name) { -String Path =GetFilePath (name); -         //Classfile for the class file to be encrypted theFile Classfile =NewFile (path); -         if(!classfile.exists ()) { -            //TODO If the file does not exist, do the appropriate processing. The exception is thrown in the general case; -}Else { +            //Folder is ready to create a file in the same directory as the file to be encrypted, which is the classfile, with the encrypted files -File folder =NewFile (classfile.getparent () + File.separator +encryptfolder); +             if(!folder.exists ()) { A folder.mkdirs (); at             } -         } -         //Cipheredclass The full path file name for the encrypted file -String Cipheredclass = classfile.getparent () + file.separator + encryptfolder + file.separator +classfile.getname (); -         Try ( -FileInputStream FileInputStream =NewFileInputStream (classfile); inBufferedinputstream bis =NewBufferedinputstream (fileinputstream); -FileOutputStream FileOutputStream =NewFileOutputStream (cipheredclass); toBufferedoutputstream BOS =NewBufferedoutputstream (FileOutputStream) +         ) { -             intdata; the              while(data = Bis.read ())! =-1) { *Bos.write (data ^ 0xFF); $             }Panax Notoginseng Bos.flush (); -}Catch(IOException e) { the e.printstacktrace (); +         } A  the         //The original unencrypted file is now deleted + Classfile.delete (); -          $         //The following sentence adds an "en" to the file, and the last generated file is Xxx.classen, which is intended to be done in order to start the server $         //Tomcat will automatically check the class file under Classespath, and if I don't add "en" then the encrypted file will be scanned by Tomcat.  -         //if it is scanned, but it is an encrypted file, the header information has been modified, then Tomcat will error, start not up. It's kind of a little trick.  -File OldFile =NewFile (path + "en")); the         if(Oldfile.exists ()) { - Oldfile.delete ();Wuyi         } theFile Cipheredfile =NewFile (cipheredclass); - Cipheredfile.renameto (oldFile); Wu cipheredfile.getparentfile (). Delete (); -     } About  $     /** - * Decryption Method -      * @paramName the file name to decrypt -      */ A     protected byte[] Decryptclass (String name) { + String Path; the         if(!name.contains (". Class"))) { -Path =Getdeffilepath (name); $}Else { thePath =name; the         } theFile Encryptedclassfile =NewFile (path); the         if(!encryptedclassfile.exists ()) { -System.out.println ("Decryptclass () File:" + path + "Not found!"); in             return NULL; the         } the         byte[] result =NULL; AboutBufferedinputstream bis =NULL; theBytearrayoutputstream BOS =NULL; the         Try { thebis =NewBufferedinputstream (NewFileInputStream (Encryptedclassfile)); +BOS =NewBytearrayoutputstream (); -             intdata; the              while(data = Bis.read ())! =-1) {BayiBos.write (data ^ 0xFF); the             } the Bos.flush (); -result =Bos.tobytearray (); -}Catch(Exception e) { the e.printstacktrace (); the}finally { the             Try { the                 if(bis! =NULL) { - bis.close (); the                 } the                 if(Bos! =NULL) { the bos.close ();94                 } the}Catch(IOException e) { the e.printstacktrace (); the             }98         } About         returnresult; -     }101 102    //gets the absolute path of the file before encryption103     Privatestring GetFilePath (string name) {104 String Path; theString str = name.substring (Name.lastindexof (".") + 1, name.length ()) + ". Class";106Path = Edcipher.class. getresource (str). toString ();107Path = path.substring (Path.indexof ("file:/") + "file:/". Length (), path.length ());108         if(System.getproperty ("Os.name"). toUpperCase (). Contains ("LINUX"))) {109Path = File.separator +path; the         }111         returnpath; the     }113  the    //gets the absolute path of the encrypted file the     Privatestring Getdeffilepath (string name) { the String Path;117String str = name.substring (Name.lastindexof (".") + 1, name.length ()) + ". Classen";118Path = Edcipher.class. getresource (str). toString ();119Path = path.substring (Path.indexof ("file:/") + "file:/". Length (), path.length ()); -         returnpath;121     }122 123    //Test124      Public Static voidMain (string[] args) { theEdcipher Edcipher =NewEdcipher ();126Edcipher.encryptclass (args[0]);127     } -}

If you want to encrypt files when ant is packaged, you need to call the main method of the class in the Build.xml configuration file to
1 <!--encrypted-2 <target name= "Encrypt" >3     <java classname= "Edcipher" Failonerror= "true" >4         <classpath refid= "Classpath.run"/>5         <arg line= " Package name + file name "/>6     </java>7 </target> for files to be encrypted

Java encryption decrypts class file, using ClassLoader to dynamically decrypt class files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.