`

java字节码加解密

    博客分类:
  • J2SE
阅读更多

一.创建KEY

class Key {  
  
    //private String keyName;  
  
    public Key() {  
  
    }  
  
    public Key(String keyName) {  
        //this.keyName = keyName;  
    }  
  
    public void createKey(String keyName) throws Exception {  
  
        SecureRandom sr = new SecureRandom();  
        KeyGenerator kg = KeyGenerator.getInstance("DES");  
        kg.init(sr);  
        SecretKey key = kg.generateKey();  
        System.out.println(key.toString());  
        byte rawKeyData[] = key.getEncoded();  
        FileOutputStream fo = new FileOutputStream(new File(keyName));  
        fo.write(rawKeyData);  
        fo.close();  
    }  
  
    public static void main(String args[]) {  
        try {  
            new Key("").createKey("d:/classLoad/key.txt");  
  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
    }  
} 

 二.加解密简单对象

public class HelloWorld {  
	  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        System.out.println("Hello world");  
    }  
  
    public static void sayHello() {  
        System.out.println("Hello 呵!");  
    }  
  
}

 三.加密

/**
 * 加密
 * @author weistar
 *
 */
public class Crypt {

	public static void main(String[] args) throws Exception {

		SecureRandom sr = new SecureRandom();
		FileInputStream fi = new FileInputStream(new File("d:/classLoad/key.txt"));
		byte rawKeyData[] = new byte[fi.available()];
		fi.read(rawKeyData);
		fi.close();
		DESKeySpec dks = new DESKeySpec(rawKeyData);
		SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, key, sr);
		FileInputStream fi2 = new FileInputStream(new File(
				"d:/classLoad/com/HelloWorld.class"));
		byte data[] = new byte[fi2.available()];
		fi2.read(data);
		fi2.close();
		byte encryptedData[] = cipher.doFinal(data);
		FileOutputStream fo = new FileOutputStream(new File(
				"d:/classLoad/com/HelloWorld.class"));
		fo.write(encryptedData);
		fo.close();
	}
}

 四.解密

/**
 * 解密
 * @author weistar
 *
 */
public class Decrypt {

	public static void main(String[] args) throws Exception {

		SecureRandom sr = new SecureRandom();
		FileInputStream fi = new FileInputStream(new File("d:/classLoad/key.txt"));
		byte rawKeyData[] = new byte[fi.available()];
		fi.read(rawKeyData);
		fi.close();
		DESKeySpec dks = new DESKeySpec(rawKeyData);
		SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, key, sr);
		FileInputStream fi2 = new FileInputStream(new File(
				"D:/classLoad/com/HelloWorld.class"));
		byte encryptedData[] = new byte[fi2.available()];
		fi2.read(encryptedData);
		fi2.close();
		byte decryptedData[] = cipher.doFinal(encryptedData);
		MyClassLoader mcl = new MyClassLoader("D:/classLoad/com");
		Class<?> cl = mcl.loadClass(decryptedData, "com.HelloWorld");
		Method mainMethod = cl.getMethod("sayHello");
		mainMethod.invoke(null, new Object[]{});
	}
}

 五.加载字节码

public class MyClassLoader extends ClassLoader {  
  
    private static String myClasspath = new String("");  
    private static Hashtable<String, Class<?>> loadClassHashTable = new Hashtable<String, Class<?>>();  
    private static Hashtable<String, Long> loadClassTime = new Hashtable<String, Long>();  
  
    public MyClassLoader() {  
  
    }  
  
    /** */  
    /** 
     * create a classloader and specify a classpath. 
     *  
     * @param myClasspath 
     *            the specified classpath name. 
     */  
    public MyClassLoader(String myClasspath) {  
        if (!myClasspath.endsWith("\\")) {  
            myClasspath = myClasspath + "\\";  
        }  
        MyClassLoader.myClasspath = myClasspath;  
    }  
  
    /** */  
    /** 
     * set the classpath 
     *  
     * @param myClasspath 
     *            the specified classpath name 
     */  
    public void SetmyClasspath(String myClasspath) {  
        if (!myClasspath.endsWith("\\")) {  
            myClasspath = myClasspath + "\\";  
        }  
        MyClassLoader.myClasspath = myClasspath;  
    }  
  
    /** */  
    /** 
     * Loads the class with the specified binary name. This method searches for 
     * classes in the same manner as the loadClass(String, boolean) method. 
     * Invoking this method is equivalent to invoking {loadClass(name,false)}. 
     *  
     * @param className 
     *            The binary name of the class. 
     *  
     * @return The resulting <tt>Class</tt> object. 
     *  
     * @throws ClassNotFoundException 
     *             If the class was not found. 
     */  
    @SuppressWarnings("unchecked")  
    public Class loadClass(String className) throws ClassNotFoundException {  
        return loadClass(className, false);  
    }  
  
    /** */  
    /** 
     * Loads the class with the specified binary name. The default 
     * implementation of this method searches for classes in the following 
     * order: 
     *  
     * Invoke {findLoadedClass(String)} to check if the class has already been 
     * loaded. 
     *  
     * Invoke {findSystemClass(String)} to load the system class. 
     *  
     * Invoke the {findClass(String)} method to find the class. 
     *  
     * If the class was found using the above steps, and the resolve flag is 
     * true, this method will then invoke the {resolveClass(Class)} method on 
     * the resulting Class object. 
     *  
     * @param name 
     *            The binary name of the class. 
     *  
     * @param resolve 
     *            If true then resolve the class. 
     *  
     * @return The resulting Class object. 
     *  
     * @throws ClassNotFoundException 
     *             If the class could not be found. 
     */  
    @SuppressWarnings("unchecked")  
    protected Class loadClass(String name, boolean resolve)  
            throws ClassNotFoundException {  
  
        try {  
            Class foundClass = findLoadedClass(name);  
  
            // check if the class has already been loaded.  
            if (foundClass != null) {  
                System.out.println("Complete to load the class: " + name);  
                return foundClass;  
            }  
  
            // if the class is systemClass, load the system class by system  
            if (name.startsWith("java.")) {  
                foundClass = findSystemClass(name);  
                loadClassHashTable.put(name, foundClass);  
                System.out.println("System is loading the class: " + name);  
                return foundClass;  
            }  
  
            // invoke the findClass() method to load the class  
            try {  
                foundClass = findClass(name);  
            } catch (Exception fnfe) {  
            }  
  
            if (resolve && (foundClass != null)) {  
                resolveClass(foundClass);  
            }  
            return foundClass;  
        } catch (Exception e) {  
            throw new ClassNotFoundException(e.toString());  
        }  
    }  
  
    /** */  
    /** 
     * Finds the class with the specified binary name.The default implementation 
     * throws a ClassNotFoundException. 
     *  
     * @param className 
     *            The binary name of the class. 
     *  
     * @return The resulting Class object. 
     *  
     * @throws ClassNotFoundException 
     *             If the class could not be found. 
     */  
    @SuppressWarnings("unchecked")  
    public Class findClass(String className) {  
  
        byte[] classData = null;  
        try {  
            classData = loadClassData(className);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        if (classData == null) {  
            return null;  
        }  
  
        System.out.println("MyClassLoader is loading : " + className + "");  
        Class c = defineClass(className, classData, 0, classData.length);  
        MyClassLoader.loadClassHashTable.put(className, c);  
        System.out.println("Complete to load the class :" + className);  
        return c;  
    }  
  
    /** */  
    /** 
     * Loads the classData with the specified binary name. This method searches 
     * for classes in the specified classpath as 
     * searchFile(myClasspath,className) method. 
     *  
     * @param name 
     *            The binary name of the class 
     *  
     * @return The resulting the classData of the class object by byte[] 
     *  
     * @throws IOException 
     *             if have some failed or interrupted I/O operations. 
     */  
    private byte[] loadClassData(String className) throws IOException {  
  
        String filePath = searchFile(myClasspath, className + ".class");  
  
        if (!(filePath == null || filePath == "")) {  
  
            System.out.println("It have found the file : " + className  
                    + ".  Begin to read the data and load the class。");  
            FileInputStream inFile = new FileInputStream(filePath);  
            byte[] classData = new byte[inFile.available()];  
            inFile.read(classData);  
            inFile.close();  
            loadClassTime.put(className, new File(filePath).lastModified());  
            return classData;  
        } else {  
  
            filePath = searchFile(myClasspath, className + ".java");  
            if (!(filePath == null || filePath == "")) {  
                System.out.println("It have found the file : " + filePath  
                        + ".  Begin to translate");  
                Runtime.getRuntime().exec("javac " + filePath);  
                try {  
                    Thread.sleep(1000);  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
                System.out.println("Translate it over : " + filePath);  
                return loadClassData(className);  
            } else {  
                System.out  
                        .println("Haven't found the file, and fail to read the classData!");  
                return null;  
            }  
        }  
    }  
  
    /** */  
    /** 
     * Loads the class with the specified binary name.The default implementation 
     * throws a ClassNotFoundException. 
     *  
     * @param classData 
     *            The data of the class. 
     * @param className 
     *            The binary name of the class. 
     *  
     * @return The resulting Class object. 
     *  
     * @throws ClassNotFoundException 
     *             If the class could not be found. 
     */  
    public Class<?> loadClass(byte[] classData, String className)  
            throws ClassNotFoundException {  
  
        System.out.println("MyClassLoader is loading : " + className + "");  
        Class<?> c = defineClass(className, classData, 0, classData.length);  
        loadClassHashTable.put(className, c);  
        System.out.println("Complete to load the class :" + className);  
  
        return c;  
    }  
  
    /** */  
    /** 
     * Loads the class with the specified binary name.The default implementation 
     * throws a ClassNotFoundException. 
     *  
     * @param className 
     *            The binary name of the class. 
     * @param jarName 
     *            The binary name of the jar that search the class from it. 
     *  
     * @return The resulting Class object. 
     *  
     * @throws ClassNotFoundException 
     *             If the class could not be found. 
     */  
    protected Class<?> loadClass(String className, String jarName)  
            throws ClassNotFoundException {  
  
        String jarPath = searchFile(myClasspath, jarName + ".jar");  
        JarInputStream in = null;  
  
        if (!(jarPath == null || jarPath == "")) {  
  
            try {  
                in = new JarInputStream(new FileInputStream(jarPath));  
                JarEntry entry;  
                while ((entry = in.getNextJarEntry()) != null) {  
                    String outFileName = entry.getName().substring(  
                            entry.getName().lastIndexOf("/") + 1,  
                            entry.getName().length());  
                    if (outFileName.equals(className + ".class")) {  
                        if (entry.getSize() == -1) {  
                            System.err.println("error : can't read the file!");  
                            return null;  
                        }  
                        byte[] classData = new byte[(int) entry.getSize()];  
                        System.out  
                                .println("It have found the file : "  
                                        + className  
                                        + ".  Begin to read the data and load the class。");  
                        in.read(classData);  
                        return loadClass(classData, className);  
                    }  
                }  
                System.out.println("Haven't found the file " + className  
                        + " in " + jarName + ".jar.");  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        } else {  
            System.out.println("Haven't found the jarFile: " + jarName  
                    + ".jar.");  
            return null;  
        }  
        return null;  
    }  
  
    /** */  
    /** 
     * Reloads the class with the specified binary name. Needn't have to restart 
     * JVM then reload the class. 
     *  
     * @param className 
     *            The binary name of the class need to reload . 
     *  
     * @return The resulting Class object. 
     *  
     * @throws ClassNotFoundException 
     *             If the class was not found. 
     */  
    public Class<?> reload(String fileName) {  
  
        String filePath = searchFile(myClasspath, fileName + ".class");  
        Long a = new File(filePath).lastModified();  
  
        if (!a.equals(loadClassTime.get(fileName))) {  
            loadClassHashTable.remove(fileName);  
            loadClassTime.remove(fileName);  
            try {  
                MyClassLoader mc2 = new MyClassLoader(myClasspath);  
                mc2.loadClass(fileName);  
            } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
            }  
        } else {  
            System.out  
                    .println("The class is the newest version , needn't reloading.");  
        }  
        return null;  
    }  
  
    /** */  
    /** 
     * search the file with the specified binary name. Needn't have to restart 
     * JVM then reload the class. 
     *  
     * @param classpath 
     *            the specified path where we search. 
     * @param fileName 
     *            The binary name of the file that want to search. 
     *  
     * @return The resulting file path. 
     */  
    public String searchFile(String classpath, String fileName) {  
  
        String cut = fileName.substring(fileName.lastIndexOf('.'), fileName  
                .length());  
        String path = fileName.substring(0, fileName.lastIndexOf('.')).replace(  
                '.', '/')  
                + cut;  
  
        File f = new File(classpath + path);  
        if (f.isFile()) {  
            return f.getPath();  
        } else {  
            String objects[] = new File(classpath).list();  
            for (int i = 0; i < objects.length; i++) {  
                if (new File(classpath + File.separator + objects[i])  
                        .isDirectory()) {  
                    String s = searchFile(classpath + objects[i]  
                            + File.separator, fileName);  
                    if (s == null || s == "") {  
                        continue;  
                    } else {  
                        return s;  
                    }  
                }  
            }  
        }  
        return null;  
    };  
  
}  
 

 

 

 

 

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    java字节码加密

    Java字节码加密是保护Java应用程序源代码安全的重要技术手段,主要是为了防止恶意用户逆向工程分析、篡改或盗取程序的核心逻辑。在Java中,字节码(Bytecode)是程序经过编译后的中间表示,可以直接由Java虚拟机...

    Java字节码加密工具.zip

    字节码加密是通过混淆、加密和解密等技术来改变Java字节码的原始结构,使得反编译后的结果变得难以理解。下面将详细介绍Java字节码加密的相关知识点: 1. **Java字节码**:Java程序在编译后生成的是字节码(.class...

    c/c++与java互通 AES加密解密

    加密过程包括四个主要步骤:字节替代、行移位、列混淆和密钥加。解密过程则是加密步骤的逆过程。 在C/C++中实现AES加密,可以使用如OpenSSL这样的库,但根据描述,我们将仅使用基本的数据结构。这可能意味着我们...

    Java字节码加密工具

    Java字节码加密工具是一种用于保护Java应用程序源代码安全的工具。在软件开发过程中,源代码是开发者的心血结晶,包含了许多重要的商业逻辑和技术细节。然而,Java的字节码(.class文件)虽然相对于源代码(.java...

    java密码加密与解密

    MD5是一种广泛使用的哈希函数,它能够将任意长度的数据转化为固定长度的128位(16字节)散列值,通常以32位十六进制数字的形式表示。由于其不可逆性,MD5常用于密码存储,但需要注意的是,由于碰撞攻击的存在,MD5并...

    基于JAVA文件加解密的实验报告

    【基于JAVA文件加解密的实验报告】 本报告聚焦于使用Java进行文件加解密的实践,主要涉及了面向对象程序设计(JAVA)课程设计,选题为文件加解密。设计目标包括利用特定加密算法对文本文件进行加密和解密,支持RSA...

    Java AES128加密解密

    Java中的AES128加密解密是信息安全领域中常见的数据保护技术。AES,全称Advanced Encryption Standard,是一种块密码标准,被广泛应用于各种场景,包括网络传输、存储数据加密等。128位是AES的一个关键参数,表示...

    java和javascript之间的DES加密解密

    在Java端解密时,需要先将Base64字符串解码回字节流。 5. **文件`DES加密解密`**: 压缩包中的文件可能包含了Java源代码和JavaScript源代码示例,以及可能的测试数据。这些文件可以直接运行,用于演示如何在Java和...

    java后台及前端js使用AES互相加解密及前端md5加密

    本主题涉及的是在Java后台与前端JavaScript之间利用AES(Advanced Encryption Standard)进行加解密,以及前端的MD5(Message-Digest Algorithm 5)加密技术。以下是关于这些知识点的详细解释: 1. **AES加密**:...

    C#和Java实现互通的RSA&DES加解密算法

    3. 解密过程:Java使用RSA私钥或DES密钥加密数据,C#接收并解密。 在实现过程中,还需要注意以下几点: - 对于RSA,确保使用相同的模数和指数进行公钥和私钥的生成。 - 对于DES,由于其密钥长度固定,需要确保在两...

    Java实现AES加密和解密算法

    在Java中实现AES(Advanced Encryption Standard)加密和解密算法主要涉及到对称密钥加密技术。AES算法是一种块密码,采用固定大小的128位(16字节)块进行加密和解密,支持128、192和256位的密钥长度。在给定的代码...

    java 基于AES实现对文件的加密 解密

    加密和解密过程都基于一系列复杂的数学运算,包括字节替换、行移位和列混淆等步骤。AES有三种密钥长度:128位、192位和256位,不同长度的密钥提供了不同的安全性级别。 在Java中,我们可以使用`javax.crypto`包来...

    Java编程实现同步序列密码的加密解密系统

    这种密码系统的优点在于加解密速度快,且对明文的每一位处理独立,适合于大量数据的实时加密。 在Java中,我们可以使用`java.security.SecureRandom`类来生成随机数,作为密钥流的种子。同时,我们可以自定义一个类...

    java密码加密解密算法代码实现

    Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。 Base64编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,...

    RSA加密算法实现以及C#与java互通加解密

    ### RSA加密算法实现以及C#与Java互通加解密 #### 一、RSA算法简介 RSA算法是一种非对称加密算法,由Ron Rivest、Adi Shamir 和 Leonard Adleman 在1977年提出,并以其三人的名字首字母命名。RSA算法的安全性基于...

    JAVA实现DES加解密文本文件

    - classes:编译后的类文件目录,这些是经过javac编译后的.java文件的字节码版本。 综上所述,这个项目提供了一个JAVA实现的DES加解密工具,具备图形用户界面,方便用户对文本文件进行加密和解密操作。通过理解DES...

    自己整理的Java实现加解密算法

    本资源“自己整理的Java实现加解密算法”提供了一套Java编程语言实现的加密和解密算法,包括AES、MD5和DES等主流的加密算法。以下是对这些算法的详细讲解: 首先,MD5(Message-Digest Algorithm 5)是一种广泛使用...

    RSA加解密Java&Android;解决长度限制亲测可用idea

    在Java中,`java.security`和`javax.crypto`包提供了必要的接口和类来实现RSA加解密。例如,`KeyPairGenerator`用于生成公钥和私钥对,`Cipher`用于进行加解密操作。 在描述中提到的"解决长度限制",这是因为在RSA...

    java的AES加密解密

    Java中的AES(Advanced Encryption Standard)加密解密是信息安全领域中常用的一种对称加密技术。AES在数据保护、网络通信和存储安全中发挥着重要作用。它以其高效性和安全性,被广泛应用于各种软件开发中。本篇将...

    Js Java Rsa 加密解密

    JavaScript、Java和RSA加密解密是信息安全领域中的关键技术,它们被广泛应用于数据传输、用户认证、Web应用安全等场景。RSA是一种非对称加密算法,以其发明者Ron Rivest、Adi Shamir和Leonard Adleman的名字命名,它...

Global site tag (gtag.js) - Google Analytics