Summary: Class in encrypted and confidential jar

Source: Internet
Author: User

1. encrypt and decrypt a single class file deployed in the JBoss middleware. The principle is to use the "Java source program encryption solution (based on classloader decryption) ()" blog;

Import Java. io. bufferedinputstream; import Java. io. bufferedoutputstream; import Java. io. fileinputstream; import Java. io. fileoutputstream; // Encryption Class file public class encryptionclass {public static void main (string [] ARGs) throws exception {bufferedinputstream Bis = new bufferedinputstream (New fileinputstream ("D: /program files/jboss-4.0.5.GA/Server/default/deploy/ICMP. war/WEB-INF/classes/COM/zzst/application/meeting/mCu/operate/rmx2000/rmx2000sender2. class "); byte [] DATA = new byte [bis. available ()]; bis. read (data); bis. close (); For (INT I = 0; I <data. length; I ++) {data [I] = (byte) (data [I] + 1);} bufferedoutputstream Bos = new bufferedoutputstream (New fileoutputstream ("D: /program files/jboss-4.0.5.GA/Server/default/deploy/ICMP. war/WEB-INF/classes/COM/zzst/application/meeting/mCu/operate/rmx2000/rmx2000sender2. class "); Bos. write (data); Bos. close ();}}
 

Package com. zzst. application. mcuutil. test;

Import java. Io. bufferedinputstream;
Import java. Io. bytearrayoutputstream;
Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. util. hashmap;
Import java. util. Map;

 

Public class myclassloader extends networkclassloader {

String classpath;

Map <string, class> loadedclasspool = new hashmap <string, class> ();

 

Public myclassloader (string classpath ){
This. classpath = classpath;
}

 

Public myclassloader (string classpath, string otherbaseurl ){
This. classpath = classpath;
Setbaseurl (otherbaseurl );
}

@ Suppresswarnings ("unchecked ")
@ Override
Public synchronized class <?> Loadclass (string name, Boolean resolve) throws classnotfoundexception {
Class claz = NULL;
If (loadedclasspool. containskey (name )){
Claz = This. loadedclasspool. Get (name );
} Else {

 

Try {
If (claz = NULL ){
Claz = super. loadclass (name, false );
If (claz! = NULL ){
System. Out. println ("system loaded successfully:" + name );
}
}
} Catch (classnotfoundexception e ){
System. Out. println ("the system cannot be loaded:" + name );
}

Try {
If (claz = NULL ){
// Decrypt the rmx2000sender2. Class file and then load it into a class
If (name. Equals ("com. zzst. application. Meeting. MCU. Operate. rmx2000.rmx2000sender2 ")){
Try {
Bufferedinputstream Bis = new bufferedinputstream (New fileinputstream (classnametopath (name )));
Byte [] DATA = new byte [bis. Available ()];
Bis. Read (data );
Bis. Close ();
For (INT I = 0; I <data. length; I ++ ){
Data [I] = (byte) (data [I]-1 );
}
// Class claz = defineclass ("hello", Data, 0, Data. Length );
System. out. println ("=============== my class loader ======================" + "com. zzst. application. meeting. MCU. operate. rmx2000.rmx2000sender2 ");
Claz = defineclass (name, Data, 0, Data. Length );
} Catch (exception e ){
E. printstacktrace ();
}
}

If (claz! = NULL ){
System. Out. println ("Custom decryption loaded successfully:" + name );
}
}
} Catch (exception e ){
System. Out. println ("Custom decryption cannot be loaded:" + name );
}

Try {
If (claz = NULL ){
Claz = findclass (name );
If (claz! = NULL ){
System. Out. println ("lib system loaded successfully:" + name );
}
}
} Catch (classnotfoundexception e ){
System. Out. println ("the Lib system cannot be loaded:" + name );
}

Try {
If (claz = NULL ){
Claz = loadbycjclassloader (name );
If (claz! = NULL ){
System. Out. println ("Custom loading successful:" + name );
}
}
} Catch (exception e ){
System. Out. println ("Custom cannot be loaded:" + name );
}

 

If (claz! = NULL ){
This. loadedclasspool. Put (name, claz );
}

 

}
If (RESOLVE ){
Resolveclass (claz );
}
Return claz;
}

 

/**
*
* Decryption and Loading
*
*
* @ Param name
* @ Return
*/
@ Suppresswarnings ("unchecked ")
Private class loadbycjclassloader (string name ){
Class claz = NULL;
Try {
Byte [] rawdata = loadclassdata (name );
If (rawdata! = NULL ){
/* Temporarily not decrypted
Byte [] classdata = decrypt (getreversecypher (this. cjcipher. getkeycode (), rawdata );
Classdata = cipherutil. Filter (classdata, this. cjcipher );
*/


Byte [] classdata = rawdata;
Claz = defineclass (name, classdata, 0, classdata. Length );
}
} Catch (exception e ){
E. printstacktrace ();
Claz = NULL;
}
Return claz;
}

Private byte [] loadclassdata (string classname ){

 

String Path = classnametopath (classname );

 

Try {

 

Inputstream ins = new fileinputstream (PATH );

 

Bytearrayoutputstream baos = new bytearrayoutputstream ();

 

Int buffer size = 4096;

 

Byte [] buffer = new byte [buffersize];

 

Int bytesnumread = 0;

 

While (bytesnumread = ins. Read (buffer ))! =-1 ){

 

Baos. Write (buffer, 0, bytesnumread );

 

}

 

Return baos. tobytearray ();

 

} Catch (ioexception e ){

 

E. printstacktrace ();

 

}

 

Return NULL;

 

}

 

Private string classnametopath (string classname ){
Return classpath + file. separatorchar + classname. Replace ('.', file. separatorchar) + ". Class ";

 

}

}

 

2. encrypt the class file in the jar package: You can encrypt the class file on the hard disk first, and then manually Replace the same class file in the jar package;

To load the class in a third-party jar package, you can inherit the urlclassloader. In an application, if you want to decrypt the class file in the jar package and then load it, you can also use the method in the urlclassloader class:

 

Package com. zzst. Action. Meeting. Meeting;

 

Import java. Io. ioexception;
Import java.net. malformedurlexception;
Import java.net. url;
Import java.net. urlclassloader;
Import java.net. urlstreamhandlerfactory;
Import java. Security. accesscontroller;
Import java. Security. codesigner;
Import java. Security. codesource;
Import java. Security. permissioncollection;
Import java. Security. privilegedexceptionaction;
Import java. util. enumeration;
Import java. util. Jar. manifest;

 

Import sun. Misc. resource;
Import sun. Misc. urlclasspath;

 

Public class networkclassloader extends urlclassloader {

 

String baseurl;

Private urlclasspath myucp;

 

Public String getbaseurl (){
Return baseurl;
}

 

Public void setbaseurl (string baseurl ){
This. baseurl = baseurl;
}

 

Public networkclassloader (){
This (new URL [] {});
}

 

/**
* The URL Ending with '/' is a directory
* Otherwise, it is a jar package.
* The parent class loader is not specified as the system class loader.
* @ Param URLs
*/
Public networkclassloader (URL [] URLs ){
Super (URLs );
Myucp = new urlclasspath (URLs );
}

 

/**
* Same as above, specify classloader
* @ Param URLs
* @ Param parent
*/
Public networkclassloader (URL [] URLs, classloader parent ){
Super (URLs, parent );
}

 

/**
* Same as above, the URL factory Processor
* @ Param URLs
* @ Param parent
* @ Param Factory
*/
Public networkclassloader (URL [] URLs, classloader parent,
Urlstreamhandlerfactory factory ){
Super (URLs, parent, factory );
}

 

/**
* [Add a baseurl]
* @ Param URL
*/
Public void addurl (string URL ){
URL uurl = NULL;
Try {
Uurl = new URL (baseurl + URL );
} Catch (malformedurlexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Addurl (uurl );
}

 

/**
* Add a URL [Add a baseurl]
*/
Protected void addurl (URL ){
Super. addurl (URL );

Myucp. addurl (URL );
}

 

/**
* Returned URL
*/
Public URL [] geturls (){
Return super. geturls ();
}

 

/**
* Search for class objects
* Search for and load the current class object from the above URLs [All jars will be opened to find the specified class]
* (You can call findclass to obtain the classes in the above URL loading package)
*/
Public class <?> Findclass (string name) throws classnotfoundexception {
// Return Super. findclass (name );
Return myfindclass (name );
}

 

/**
* This method is copied from the urlclassloader class and used to read class files from third-party jar packages.
*/
Protected class <?> Myfindclass (final string name)
Throws classnotfoundexception
{
Try {
Return (class)
Accesscontroller. doprivileged (New privilegedexceptionaction (){
Public object run () throws classnotfoundexception {
String Path = Name. Replace ('.', '/'). Concat (". Class ");
Resource res = myucp. getresource (path, false );
If (res! = NULL ){
Try {
Return defineclass (name, Res );
} Catch (ioexception e ){
Throw new classnotfoundexception (name, e );
}
} Else {
Throw new classnotfoundexception (name );
}
}
}, Accesscontroller. getcontext ());
} Catch (Java. Security. privilegedactionexception PAE ){
Throw (classnotfoundexception) Pae. getexception ();
}
}

Private class defineclass (string name, resource res) throws ioexception {
Int I = Name. lastindexof ('.');
URL url = res. getcodesourceurl ();
If (I! =-1 ){
String pkgname = Name. substring (0, I );
// Check if package already loaded.
Package PKG = getpackage (pkgname );
Manifest man = res. getmanifest ();
If (PKG! = NULL ){
// Package found, so check package sealing.
If (PKG. issealed ()){
// Verify that code source URL is the same.
If (! PKG. issealed (URL )){
Throw new securityexception (
"Sealing violation: Package" + pkgname + "is sealed ");
}

 

} Else {
// Make sure we are not attempting to seal the package

}
} Else {
If (man! = NULL ){
Definepackage (pkgname, man, URL );
} Else {
Definepackage (pkgname, null, null );
}
}
}
// Now read the class bytes and define the class
Java. NiO. bytebuffer BB = res. getbytebuffer ();
If (BB! = NULL ){
// Use (direct) bytebuffer:
Codesigner [] signers = res. getcodesigners ();
Codesource cs = new codesource (URL, signers );
Return defineclass (name, BB, CS );
} Else {
Byte [] B = res. getbytes ();
System. Out. println (name );

// Decrypt the rmx2000sender2. Class file in zzmcufv. jar and load it into a class
If (name. Equals ("com. zzst. application. Meeting. MCU. Operate. rmx2000.rmx2000sender2 ")){
For (Int J = 0; j <B. length; j ++ ){
B [J] = (byte) (B [J]-1 );
}
}
// Must read certificates after reading bytes.
Codesigner [] signers = res. getcodesigners ();
Codesource cs = new codesource (URL, signers );
Return defineclass (name, B, 0, B. length, CS );
}
}

 


/**
* Search for resources [custom relative URL search path]
* Search for the resource with the current name from the above URLs
* This must be rewritten because it is public.
*/
Public URL findresource (string name ){
URL url = NULL;
Try {
Url = new URL (baseurl + name );
} Catch (malformedurlexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Return URL;
}

 

/**
* Search for the resource list [URL search path]
*/
Public enumeration <URL> findresources (string name) throws ioexception {
Return super. findresources (name );
}

 

/**
* In the current classloader, define a new package. The package attribute is specified by manifest. The source file of this package
*/
Protected package definepackage (string name, manifest man, URL)
Throws illegalargumentexception {
Return super. definepackage (name, man, URL );
}

 

/**
* Load path permission
*/
Protected permissioncollection getpermissions (codesource ){
Return super. getpermissions (codesource );
}
}

 

This can be called in the Business Code:

Networkclassloader loader = new networkclassloader (); loader. setbaseurl ("file: // D: \ Program Files \ jboss-4.0.5.GA \ Server \ Default \ deploy \ ICMP. war \ WEB-INF \ Lib \ "); loader. addurl ("Comm. jar "); loader. addurl ("dom4j-1.6.1.jar"); loader. addurl ("log4j. jar "); loader. addurl ("commons-io-1.3.2.jar"); loader. addurl ("commons-logging-1.0.4.jar"); loader. addurl ("zzmcufv. jar "); try {class clazz = loader. findclass ("com. zzst. application. meeting. MCU. operate. rmx2000.rmx2000sender2 "); system. out. println (clazz. getname (); Method taskmethod = clazz. getmethod ("sendpost", String. class, String. class); // then we can use the reflected taskmethod. invoke (null, "http: // 10.1.6.30", "abcdefg");} catch (exception e) {e. printstacktrace ();}

 

 

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.