精华内容
下载资源
问答
  • // 加密解密只要offset一致即可 public static final int offset = Integer.MIN_VALUE + 10086; // 加密 public static String encryption(String s) { StringBuilder sb = new StringBuilder(); ...
    import java.util.Base64;
    
    public class Encryption {
    	
    	// 加密和解密只要offset一致即可
    	public static final int offset = Integer.MIN_VALUE + 10086;
    	
    	// 加密
    	public static String encryption(String s) {
    		
    		StringBuilder sb = new StringBuilder();
    		
    		for (int i = 0; i < s.length(); i++) {
    			sb.append("" + (char)(((int)s.charAt(i)) + offset));
    		}
    		
    		return new StringBuilder(Base64.getEncoder().encodeToString(new String(sb.toString()).getBytes())).reverse().toString();
    	}
    	
    	// 解密
    	public static String decryption(String s) {
    		
    		s = new String(Base64.getDecoder().decode(new StringBuilder(s).reverse().toString()));
    		
    		StringBuilder sb = new StringBuilder();
    		
    		for (int i = 0; i < s.length(); i++) {
    			sb.append((char)(((int)s.charAt(i)) - offset));
    		}
    		
    		return sb.toString();
    	}
    
    	public static void main(String[] args) {
    		String str = "加密字符串";
            // 使用的时候可嵌套多层,嵌套越多密文越长
    		System.out.println(encryption(encryption(str)));
    		System.out.println(decryption(decryption(encryption(encryption(str)))));
    	}
    }
    

     

    展开全文
  • 自定义加密解密类加载器 测试简单的class文件加密解密(取反操作)。取反加密只是一个简单示例。 加密工具类(字节按位取反) package com.feng.ClassTest; import java.io.File; import java.io....

    如果想看一下简单的类加载器怎么自定义,可以跳转简单自定义类加载器

    自定义加密解密类加载器
    测试简单的class文件加密解密(取反操作)。取反加密只是一个简单示例。

    加密工具类(字节按位取反)

    package com.feng.ClassTest;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     * 加密工具类
     * @author feng
     *
     */
    
    public class EncrpUtil {
    	
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		encrpt("E:\\myjava\\HelloWorld.class", "E:\\myjava\\temp\\HelloWorld.class");
    	}
    	
    	public static void encrpt(String src, String dest) {
    		
    		FileInputStream fis = null;
    		FileOutputStream fos = null;
    		
    		try {
    			fis = new FileInputStream(src);
    			fos = new FileOutputStream(dest);
    			
    			int temp = -1;
    			while((temp = fis.read()) != -1) {
    				fos.write(temp^0xff);	//异或,每个字节按位取反
    			}
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			
    			try {
    				if(fis != null) {
    					fis.close();
    				}
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    			try {
    				if(fos != null) {
    					fos.close();
    				}
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    		}
    	}
    }
    
    

    解密类加载器

    package com.feng.ClassTest;
    
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    /**
     * 加载文件系统加密后的class字节码的类加载器
     * @author feng
     *
     */
    
    public class DecreptClassLoader extends ClassLoader {
    	
    	private String rootDir;
    	
    	public DecreptClassLoader(String rootDir) {
    		this.rootDir = rootDir;
    	}
    	
    	@Override
    	protected Class<?> findClass(String name) throws ClassNotFoundException {
    		
    		Class<?> c = null;
    		
    		byte[] classData = getClassData(name);	// 自定义方法获取类字节码
    		if(classData == null) {
    			throw new ClassNotFoundException();	// 如果字节数组为空,抛出异常
    		} else {
    			try {
    				c = defineClass(name, classData, 0, classData.length);
    			} catch (ClassFormatError e){	// 加载错误
    				e.printStackTrace();
    				c = null;
    			}
    
    		}
    		
    		return c;
    		
    	}
    	
    	private byte[] getClassData(String classname) {
    		// 拼出类class文件地址
    		String path = rootDir + "/" + classname.replace('.', '/') + ".class";
    		
    		InputStream fis = null;
    		ByteArrayOutputStream baos = new ByteArrayOutputStream();
    		try {
    			fis = new FileInputStream(path);
    			
    			int temp = -1;
    			while((temp = fis.read()) != -1) {
    				baos.write(temp^0xff);	//异或,每个字节按位取反
    			}
    			
    			return baos.toByteArray();
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			
    			return null;
    		} finally {
    			
    			try {
    				if(fis != null) {
    					fis.close();
    				}
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    			try {
    				if(baos != null) {
    					baos.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			
    		}
    		
    	}
    	
    }
    
    

    测试自定义解密类加载器

    package com.feng.ClassTest;
    
    public class Demo04 {
    	
    	public static void main(String[] args) throws ClassNotFoundException {
    
    		//加密后的class文件,正常的类加载器 无法加载,会报FormatError错误
    		//FileSystemClassLoader loader = new FileSystemClassLoader("E:\\myjava\\temp");
    		//Class<?> c = loader.findClass("HelloWorld");
    		//System.out.println(c);
    		
    		// 使用解密类加载器
    		DecreptClassLoader loader = new DecreptClassLoader("E:\\myjava\\temp");
    		Class<?> c = loader.loadClass("HelloWorld");
    		System.out.println(c);
    		
    	}
    
    }
    
    展开全文
  • 简单自定义 字节加1 package game01; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels....

    简单自定义 字节加1 有用记得点个赞

    package game01;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.channels.FileChannel;
    import java.util.Scanner;
    
    public class Tool {
    	public static FileInputStream fis =null;
    	public static FileOutputStream fos =null;
    	public static long start;//计时
    	public static long end; 
    	public static String jiamilj = null;
    	public static String jiemilj = null;
    	public static FileChannel fc = null;//文件大小
    	
    	
    	public static void main(String []args) throws IOException{
    		
    		Scanner in = new Scanner(System.in);
    		System.out.println("你要加密还是解密:");
    		String input = in.next();
    		
    		if(input.equals("加密")){
    			
    			Scanner in01 = new Scanner(System.in);
    			System.out.println("你要加密的文件路径:(E:\\a.txt):");
    			String input01 = in01.next();
    			System.out.println(input01);
    			
    			jiami(input01);
    			System.out.println("加密成功,加密路径:"+jiamilj);
    			System.out.println("加密用时"+(end-start)+"毫秒");
    			size(1);
    			System.out.println("文件大小"+fc.size()+"Byte");
    			fis.close();
    			fos.close();
    		}else{
    			Scanner in02 = new Scanner(System.in);
    			System.out.println("你要解密的文件路径:(E:\\b.txt):");
    			String input02 = in.next();
    			jiemi(input02);
    			System.out.println("解密成功,解密路径为:"+jiemilj);
    			System.out.println("解密密用时"+(end-start)+"毫秒");
    			size(2);
    			System.out.println("文件大小"+fc.size()+"Byte");
    			fis.close();
    			fos.close();
    		}	
    		
    		
    	}
    	
    	
    	//加密
    	public static void jiami(String input02) throws IOException{
    		start = System.currentTimeMillis();
    		in01(input02);
    		end = System.currentTimeMillis();
    	}
    	//解密
    	public static void jiemi(String input02) throws IOException{
    		start = System.currentTimeMillis();
    		in02(input02);
    		end = System.currentTimeMillis();
    	}
    	
    	
    	//配套加密
    	public static void in01(String input03) throws IOException{
    		 fis = new FileInputStream(input03);		
    		int i;  //核心代码  
    		while((i=fis.read())!=-1){			
    			out01(i);
    		}
    		
    	}	
    	public static void out01(int i) throws IOException{
    		 fos = new FileOutputStream("E:\\b.txt",true);
    		fos.write(i+1);	
    		jiamilj = "E:\\b.txt";
    	}
    	
    	
    	//配套解密
    	public static void in02(String input03) throws IOException{
    		fis = new FileInputStream(input03);		
    		int i;  //核心代码  
    		while((i=fis.read())!=-1){
    			out02(i);
    		}	
    	}
    	public static void out02(int i) throws IOException{
    		 fos = new FileOutputStream("E:\\c.txt",true);
    		fos.write(i-1);	
    		jiemilj = "E:\\c.txt";
    	}
    	
    	//求文件大小
    	public static void size(int s) throws FileNotFoundException{
    		if(s==1){
    			FileInputStream fis01 = new FileInputStream("E:\\b.txt");
    			fc = fis01.getChannel();
    		}else{
    			FileInputStream fis01 = new FileInputStream("E:\\c.txt");
    			fc = fis01.getChannel();
    		}
    		
    	}
    
    }
    
    展开全文
  • 包括java自定义加密解密实例,异或加密解密实例,AES加密解密,DES加密解密 对文件加密建议使用DES方式 技术学习交流:635278789
  • Tomcat自定义classLoader加密解密

    千次阅读 2014-09-06 22:57:17
    Tomcat自定义classLoader加密解密

    class很好反编译,所以需要对class文件先进行加密,然后使用自己的classloader进行解密并加载。

    【步骤】

    大概分两步:

    1.对class文件进行加密

    2.写解密class文件并加载的classloader

    3.将这个classloader加入到tomcat中,也就是使tomcat可以调用到这个classloader

     

    【加密】

    1.思路

    字节流读取class文件,进行简单的移位

    2.实现

    做了一个小程序,实现了对某文件夹下所有class文件字节流读取,并+2位的加密方式

    3.说明

    swing是使用myeclipse的插件做的,可能比较乱

     

    【classloader】

    import java.io.ByteArrayOutputStream;  
    import java.io.FileInputStream;  
    import java.io.IOException;  
      
    import org.apache.catalina.loader.WebappClassLoader;  
      
    /** 
     * 自己的ClassLoader 
     * 用于解密加密过的class文件并加载 
     * @author uikoo9 
     */  
    public class MyClassLoader extends WebappClassLoader{  
      
        /** 
         * 默认构造器 
         */  
        public MyClassLoader() {  
            super();  
        }  
      
        /** 
         * 默认构造器 
         * @param parent 
         */  
        public MyClassLoader(ClassLoader parent) {  
            super(parent);  
        }  
      
        /* (non-Javadoc) 
         * @see org.apache.catalina.loader.WebappClassLoader#findClass(java.lang.String) 
         */  
        public Class<?> findClass(String name) throws ClassNotFoundException {  
            byte[] classBytes = null;  
              
            try {  
                classBytes = loadClassBytes(name);  
            } catch (Exception e) {  
                throw new ClassNotFoundException(name);  
            }  
              
            Class<?> cl= defineClass(name, classBytes, 0, classBytes.length);  
            if(cl == null) throw new ClassNotFoundException(name);  
              
            return cl;  
        }  
          
        /** 
         * 简单的解密 
         * @param name 
         * @return 
         * @throws IOException 
         */  
        private byte[] loadClassBytes(String name) throws IOException{  
            String cname = name.replace('.', '/') + ".class";  
              
            FileInputStream in = new FileInputStream(cname);  
            try {  
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();  
                  
                int ch;  
                while((ch = in.read()) != -1){  
                    if(cname.contains("uikoo9")){// 如果包含uikoo9说明是自己写的class,进行解密  
                        System.out.println("++");  
                        buffer.write((byte)(ch-2));  
                    }else{  
                        buffer.write((byte)ch);  
                    }  
                }  
                in.close();  
                  
                return buffer.toByteArray();  
            }finally{  
                in.close();  
            }  
        }  
    }  
    

    【加入到tomcat中】

    1.网上

    网上很多文章都问到tomcat怎么使用自己的classloader,但是说明白的几乎没有,

    最后自己读了tomcat官网的文档,找到了答案,

    地址:http://tomcat.apache.org/tomcat-6.0-doc/config/loader.html

    2.方法

    说简单点,就是在tomcat\conf\context.xml中添加以下这段代码:

    <Loader loaderClass="com.uikoo9.MyClassLoader"></Loader >  

    3.classloader

    但是注意,这里的com.uikoo9.MyClassLoader并不是项目中的,

    而是需要放到tomcat\lib下。

     

    【新的问题】

    1.这个自己写的classloader确实起作用的,但是问题也随之而来,

    原来tomcat在调用classloader之前会调用一个自己的classparser类来对class文件进行解析

    2.classparser

    位于org\apache\tomcat\util\bcel\classfile下的ClassParser.java,

    源代码:

    /* 
     *  Licensed to the Apache Software Foundation (ASF) under one or more 
     *  contributor license agreements.  See the NOTICE file distributed with 
     *  this work for additional information regarding copyright ownership. 
     *  The ASF licenses this file to You under the Apache License, Version 2.0 
     *  (the "License"); you may not use this file except in compliance with 
     *  the License.  You may obtain a copy of the License at 
     * 
     *      http://www.apache.org/licenses/LICENSE-2.0 
     * 
     *  Unless required by applicable law or agreed to in writing, software 
     *  distributed under the License is distributed on an "AS IS" BASIS, 
     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
     *  See the License for the specific language governing permissions and 
     *  limitations under the License. 
     * 
     */  
    package org.apache.tomcat.util.bcel.classfile;  
      
    import java.io.BufferedInputStream;  
    import java.io.DataInputStream;  
    import java.io.FileInputStream;  
    import java.io.IOException;  
    import java.io.InputStream;  
    import java.util.zip.ZipEntry;  
    import java.util.zip.ZipFile;  
      
    import org.apache.tomcat.util.bcel.Constants;  
      
    /** 
     * Wrapper class that parses a given Java .class file. The method <A 
     * href ="#parse">parse</A> returns a <A href ="JavaClass.html"> 
     * JavaClass</A> object on success. When an I/O error or an 
     * inconsistency occurs an appropiate exception is propagated back to 
     * the caller. 
     * 
     * The structure and the names comply, except for a few conveniences, 
     * exactly with the <A href="ftp://java.sun.com/docs/specs/vmspec.ps"> 
     * JVM specification 1.0</a>. See this paper for 
     * further details about the structure of a bytecode file. 
     * 
     * @version $Id: ClassParser.java 992409 2010-09-03 18:35:59Z markt $ 
     * @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>  
     */  
    public final class ClassParser {  
      
        private DataInputStream file;  
        private boolean fileOwned;  
        private String file_name;  
        private String zip_file;  
        private int class_name_index, superclass_name_index;  
        private int major, minor; // Compiler version  
        private int access_flags; // Access rights of parsed class  
        private int[] interfaces; // Names of implemented interfaces  
        private ConstantPool constant_pool; // collection of constants  
        private Field[] fields; // class fields, i.e., its variables  
        private Method[] methods; // methods defined in the class  
        private Attribute[] attributes; // attributes defined in the class  
        private boolean is_zip; // Loaded from zip file  
        private static final int BUFSIZE = 8192;  
      
      
        /** 
         * Parse class from the given stream. 
         * 
         * @param file Input stream 
         * @param file_name File name 
         */  
        public ClassParser(InputStream file, String file_name) {  
            this.file_name = file_name;  
            fileOwned = false;  
            String clazz = file.getClass().getName(); // Not a very clean solution ...  
            is_zip = clazz.startsWith("java.util.zip.") || clazz.startsWith("java.util.jar.");  
            if (file instanceof DataInputStream) {  
                this.file = (DataInputStream) file;  
            } else {  
                this.file = new DataInputStream(new BufferedInputStream(file, BUFSIZE));  
            }  
        }  
      
      
        /** 
         * Parse the given Java class file and return an object that represents 
         * the contained data, i.e., constants, methods, fields and commands. 
         * A <em>ClassFormatException</em> is raised, if the file is not a valid 
         * .class file. (This does not include verification of the byte code as it 
         * is performed by the java interpreter). 
         * 
         * @return Class object representing the parsed class file 
         * @throws  IOException 
         * @throws  ClassFormatException 
         */  
        public JavaClass parse() throws IOException, ClassFormatException {  
            ZipFile zip = null;  
            try {  
                if (fileOwned) {  
                    if (is_zip) {  
                        zip = new ZipFile(zip_file);  
                        ZipEntry entry = zip.getEntry(file_name);  
                          
                        if (entry == null) {  
                            throw new IOException("File " + file_name + " not found");  
                        }  
                          
                        file = new DataInputStream(new BufferedInputStream(zip.getInputStream(entry),  
                                BUFSIZE));  
                    } else {  
                        file = new DataInputStream(new BufferedInputStream(new FileInputStream(  
                                file_name), BUFSIZE));  
                    }  
                }  
                /****************** Read headers ********************************/  
                // Check magic tag of class file  
                readID();  
                // Get compiler version  
                readVersion();  
                /****************** Read constant pool and related **************/  
                // Read constant pool entries  
                readConstantPool();  
                // Get class information  
                readClassInfo();  
                // Get interface information, i.e., implemented interfaces  
                readInterfaces();  
                /****************** Read class fields and methods ***************/  
                // Read class fields, i.e., the variables of the class  
                readFields();  
                // Read class methods, i.e., the functions in the class  
                readMethods();  
                // Read class attributes  
                readAttributes();  
                // Check for unknown variables  
                //Unknown[] u = Unknown.getUnknownAttributes();  
                //for(int i=0; i < u.length; i++)  
                //  System.err.println("WARNING: " + u[i]);  
                // Everything should have been read now  
                //      if(file.available() > 0) {  
                //        int bytes = file.available();  
                //        byte[] buf = new byte[bytes];  
                //        file.read(buf);  
                //        if(!(is_zip && (buf.length == 1))) {  
                //          System.err.println("WARNING: Trailing garbage at end of " + file_name);  
                //          System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf));  
                //        }  
                //      }  
            } finally {  
                // Read everything of interest, so close the file  
                if (fileOwned) {  
                    try {  
                        if (file != null) {  
                            file.close();  
                        }  
                        if (zip != null) {  
                            zip.close();  
                        }  
                    } catch (IOException ioe) {  
                        //ignore close exceptions  
                    }  
                }  
            }  
            // Return the information we have gathered in a new object  
            return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor,  
                    access_flags, constant_pool, interfaces, fields, methods, attributes);  
        }  
      
      
        /** 
         * Read information about the attributes of the class. 
         * @throws  IOException 
         * @throws  ClassFormatException 
         */  
        private final void readAttributes() throws IOException, ClassFormatException {  
            int attributes_count;  
            attributes_count = file.readUnsignedShort();  
            attributes = new Attribute[attributes_count];  
            for (int i = 0; i < attributes_count; i++) {  
                attributes[i] = Attribute.readAttribute(file, constant_pool);  
            }  
        }  
      
      
        /** 
         * Read information about the class and its super class. 
         * @throws  IOException 
         * @throws  ClassFormatException 
         */  
        private final void readClassInfo() throws IOException, ClassFormatException {  
            access_flags = file.readUnsignedShort();  
            /* Interfaces are implicitely abstract, the flag should be set 
             * according to the JVM specification. 
             */  
            if ((access_flags & Constants.ACC_INTERFACE) != 0) {  
                access_flags |= Constants.ACC_ABSTRACT;  
            }  
            if (((access_flags & Constants.ACC_ABSTRACT) != 0)  
                    && ((access_flags & Constants.ACC_FINAL) != 0)) {  
                throw new ClassFormatException("Class " + file_name + " can't be both final and abstract");  
            }  
            class_name_index = file.readUnsignedShort();  
            superclass_name_index = file.readUnsignedShort();  
        }  
      
      
        /** 
         * Read constant pool entries. 
         * @throws  IOException 
         * @throws  ClassFormatException 
         */  
        private final void readConstantPool() throws IOException, ClassFormatException {  
            constant_pool = new ConstantPool(file);  
        }  
      
      
        /** 
         * Read information about the fields of the class, i.e., its variables. 
         * @throws  IOException 
         * @throws  ClassFormatException 
         */  
        private final void readFields() throws IOException, ClassFormatException {  
            int fields_count;  
            fields_count = file.readUnsignedShort();  
            fields = new Field[fields_count];  
            for (int i = 0; i < fields_count; i++) {  
                fields[i] = new Field(file, constant_pool);  
            }  
        }  
      
      
        /******************** Private utility methods **********************/  
        /** 
         * Check whether the header of the file is ok. 
         * Of course, this has to be the first action on successive file reads. 
         * @throws  IOException 
         * @throws  ClassFormatException 
         */  
        private final void readID() throws IOException, ClassFormatException {  
            int magic = 0xCAFEBABE;  
            if (file.readInt() != magic) {  
                throw new ClassFormatException(file_name + " is not a Java .class file");  
            }  
        }  
      
      
        /** 
         * Read information about the interfaces implemented by this class. 
         * @throws  IOException 
         * @throws  ClassFormatException 
         */  
        private final void readInterfaces() throws IOException, ClassFormatException {  
            int interfaces_count;  
            interfaces_count = file.readUnsignedShort();  
            interfaces = new int[interfaces_count];  
            for (int i = 0; i < interfaces_count; i++) {  
                interfaces[i] = file.readUnsignedShort();  
            }  
        }  
      
      
        /** 
         * Read information about the methods of the class. 
         * @throws  IOException 
         * @throws  ClassFormatException 
         */  
        private final void readMethods() throws IOException, ClassFormatException {  
            int methods_count;  
            methods_count = file.readUnsignedShort();  
            methods = new Method[methods_count];  
            for (int i = 0; i < methods_count; i++) {  
                methods[i] = new Method(file, constant_pool);  
            }  
        }  
      
      
        /** 
         * Read major and minor version of compiler which created the file. 
         * @throws  IOException 
         * @throws  ClassFormatException 
         */  
        private final void readVersion() throws IOException, ClassFormatException {  
            minor = file.readUnsignedShort();  
            major = file.readUnsignedShort();  
        }  
    }  
    

    3.问题

    发现这个解析类的文件会先去判断class的头信息来确定是不是class文件,

    但是由于我们对class进行了加密,所以头信息变了,所以这个解析class文件的类会报错,也就不会调用到classloader了

     

    【继续】

    文章有点长,不知道有人有耐心看完不。

    1.上面的问题折腾了一天,才发现是自己解密的部分有问题,

    2.不过也是有收获的,发现自定写的loader只能加载非class的文件,而不能加载class

    3.意思就是说,你需要将原来的class文件加密并改变文件后缀,然后配合自己的loader使用

    【delegate】

    由于自己英语水平有限,所以之前的tomcat文章一知半解,

    通过今天的研究发现context.xml中的delegate属性的用法。

    1.loader的代码:

    package com.uikoo9.loader;  
      
    import java.io.ByteArrayOutputStream;  
    import java.io.FileInputStream;  
    import java.io.IOException;  
      
    import org.apache.catalina.loader.WebappClassLoader;  
      
    /** 
     * 自定义的classloader 
     * 可以解密文件并加载 
     * @author uikoo9 
     */  
    public class UClassLoader extends WebappClassLoader{  
          
        /** 
         * 默认构造器 
         */  
        public UClassLoader() {  
            super();  
        }  
      
        /** 
         * 默认构造器 
         * @param parent 
         */  
        public UClassLoader(ClassLoader parent) {  
            super(parent);  
        }  
      
        /* (non-Javadoc) 
         * @see org.apache.catalina.loader.WebappClassLoader#findClass(java.lang.String) 
         */  
        public Class<?> findClass(String name) throws ClassNotFoundException {  
            byte[] classBytes = null;  
            try {  
                if(name.contains("uikoo9")){  
                    System.out.println("++++++" + name);  
                    classBytes = loadClassBytesEncrypt(name);  
                }else{  
                    System.out.println("-------" + name);  
                    classBytes = loadClassBytesDefault(name);  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
      
            Class<?> cl = defineClass(name, classBytes, 0, classBytes.length);  
            if (cl == null)  
                throw new ClassNotFoundException(name);  
            return cl;  
        }  
          
        @Override  
        public Class<?> loadClass(String name) throws ClassNotFoundException {  
            if(name.contains("uikoo9")){  
                return findClass(name);  
            }else{  
                return super.loadClass(name);  
            }  
        }  
      
        /** 
         * 加载加密后的class字节流 
         * @param name 
         * @return 
         * @throws IOException 
         */  
        private byte[] loadClassBytesEncrypt(String name) throws IOException {  
            String cname = name.replace('.', '/') + ".uikoo9";  
            FileInputStream in = null;  
            in = new FileInputStream(cname);  
            try {  
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();  
                int ch;  
                while ((ch = in.read()) != -1) {  
                    buffer.write((byte)(ch - 2));  
                }  
                in.close();  
                return buffer.toByteArray();  
            } finally {  
                in.close();  
            }  
        }  
          
        /** 
         * 加载普通的class字节流 
         * @param name 
         * @return 
         * @throws IOException 
         */  
        private byte[] loadClassBytesDefault(String name) throws IOException {  
            String cname = name.replace('.', '/') + ".class";  
            FileInputStream in = null;  
            in = new FileInputStream(cname);  
            try {  
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();  
                int ch;  
                while ((ch = in.read()) != -1) {  
                    buffer.write((byte)ch);  
                }  
                in.close();  
                return buffer.toByteArray();  
            } finally {  
                in.close();  
            }  
        }  
    }  
    

    2.delegate="false"时,启动tomcat:

    <Loader loaderClass="com.uikoo9.loader.UClassLoader" delegate="false"></Loader >  


    3.delegate="true"时,启动tomcat:

    <Loader loaderClass="com.uikoo9.loader.UClassLoader" delegate="true"></Loader >  

    4.总结

    delegate为true的时候自定义的loader只用来加载自己的代码

     

    【新问题】

    以上的代码整理一下,启动tomcat,没有报错,

    但是当点击页面的时候,也就是向后台请求的时候依然报错,

     

    【end】

    经过中午的挣扎,这个问题终于解决了,

    注意,这个只适合没有spring的,因为spring有自己的classloader。

    【classloader】

     1.代码: 

    import java.io.ByteArrayOutputStream;  
    import java.io.FileInputStream;  
    import java.io.IOException;  
      
    import org.apache.catalina.loader.WebappClassLoader;  
      
    /** 
     * 自定义的classloader 
     * 可以解密文件并加载 
     * @author uikoo9 
     */  
    public class UClassLoader extends WebappClassLoader{  
          
        /** 
         * 默认构造器 
         */  
        public UClassLoader() {  
            super();  
        }  
      
        /** 
         * 默认构造器 
         * @param parent 
         */  
        public UClassLoader(ClassLoader parent) {  
            super(parent);  
        }  
      
        /* (non-Javadoc) 
         * @see org.apache.catalina.loader.WebappClassLoader#findClass(java.lang.String) 
         */  
        public Class<?> findClass(String name) throws ClassNotFoundException {  
            if(name.contains("uikoo9")){  
                return findClassEncrypt(name);  
            }else{  
                return super.findClass(name);  
            }  
        }  
          
        /** 
         * 查找class 
         * @param name 
         * @return 
         * @throws ClassNotFoundException 
         */  
        private Class<?> findClassEncrypt(String name) throws ClassNotFoundException{  
            byte[] classBytes = null;  
            try {  
                System.out.println("++++++" + name);  
                classBytes = loadClassBytesEncrypt(name);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
      
            Class<?> cl = defineClass(name, classBytes, 0, classBytes.length);  
            if (cl == null)  
                throw new ClassNotFoundException(name);  
            return cl;  
        }  
          
        /** 
         * 加载加密后的class字节流 
         * @param name 
         * @return 
         * @throws IOException 
         */  
        private byte[] loadClassBytesEncrypt(String name) throws IOException {  
            String basepath = "Z:/program/workspaces/_work_03_bzb/WebRoot/WEB-INF/classes/";// 项目物理地址  
            String cname = basepath + name.replace('.', '/') + ".uikoo9";  
            System.out.println(cname);  
            FileInputStream in = new FileInputStream(cname);  
            try {  
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();  
                int ch;  
                while ((ch = in.read()) != -1) {  
                    buffer.write((byte)(ch - 2));  
                }  
                in.close();  
                return buffer.toByteArray();  
            } finally {  
                in.close();  
            }  
        }  
    }  
    

    【加入到tomcat】

    1.context.xml

    找到tomcat下contex.xml,在context之间加入以下代码:

    <Loader loaderClass="com.uikoo9.loader.UClassLoader" delegate="true"></Loader>  

    其中loaderClass就是自己写loader,delegate=“true”的意思是只解密非系统的class和jar

     

    2.添加loader 

    将自己写的loader的class文件放到tomcat\lib下

      

    【开始】

     1.使用加密程序对classes下所有文件加密,加密之后所有的class文件后缀变为uikoo9,可以自己修改源代码

     2.将原classes文件夹删除,将加密后的classes文件夹复制进去

     3.修改context.xml

     4.tomcat\lib下添加loader.class

     5.启动tomcat


    原文:http://blog.csdn.net/uikoo9/article/details/17281403

    展开全文
  • 在实际项目中,我们经常需要对数据进行加密,保障数据不被解密,我们可以写一个简单的加密方式进行可逆加密加密的核心在于将16进制进行重新对应,比如说加密时将0改为3,反过来解密时将3改为0. import java....
  • java自定义加密算法

    2018-08-10 19:51:42
    java实现的自定义算法。 
  • } /** * 对使用AES加密算法的密文进行解密 * @param res 需要解密的密文 * @param key 秘钥 * @return */ public static String AESdecode(String res, String key) { return keyGeneratorES(res, AES, key, ...
  • 自定义classloader加密java程序

    千次阅读 2013-08-29 15:57:28
    1. 生成密钥用于在des算法中加密。  2. classloader类中动态的解密class,并且通过反射机制执行main方法。  3. 对classloader类进行高质量的混淆。  首先需要生成des算法中的key:  Java代码  ...
  • 类加载器原理 将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区中的运行时数据结构,在堆中生成一个代表这个类的java.lang.Class对象,作为...4、自定义类加载器(Java编写) 来测试一下ClassL...
  • import java.io.UnsupportedEncodingException; public class Base64 {  private static char[] base64EncodeChars = new char[]{  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',  'I', 'J', 'K', 'L',...
  • JAVA加密解密---自定义类加载器应用
  • java课程设计加密解密

    2011-06-19 14:15:12
    java课程设计文件加密解密 自定义加密程序
  • JAVA加密解密自定义类加载器应用

    千次阅读 2007-07-07 14:00:00
    下面是自定义的CLASSLOADER在JAVA加密解密方面的一些研究。 JAVA安全 JAVA是解释执行的语言,对于不同的操作平台都有相应的JVM对字节码文件进行解释执行。而这个字节码文件,也就是我们平时所看到的每一个.class...
  • 自定义classloader实现java程序加密 背景 项目使用java语言开发,发布包会整合到C++客户端,直接安装到用户机器上,不同于之前常见的后端服务发布,这种发布能让用户直接接触到java发布包,由于java语言的特性,有...
  • 使用jfinalQ-encrypt开源软件。对项目的class文件加密,防止反编译,可自定义加密解密算法,支持tomcat部署。
  • AES+自定义密钥实现加密解密(前端+后端) 1 背景 ​ 项目需要将手机号在后端接口加密,前端进行解密并进行手机号脱敏 ​ 注意:本案例只演示了**ECB加密方式**,其他加密方式(CBC CTR OFB CFB)暂未涉及 ​ 多说...
  • JAVA加密解密---自定义类加载器应用 Posted on 2007-04-22 11:09 久城 阅读(2683) 评论(5) 编辑 收藏 所属分类: Java理解笔记 最近在研究JAVA CLASS LOADING技术,已实现了一个自定义的加载器。对目前自定义加载...
  • java json接口加密解密

    千次阅读 2019-09-23 12:24:06
    java json接口加密解密 对json接口进行加密解密, 这里实现的方式是 解密使用自定义过滤器 1、启动类加注解@ServletComponentScan @SpringBootApplication @ServletComponentScan public class TestWebApplication {...
  • java加密解密练习

    2019-09-03 22:25:21
    java加密解密练习1. 实验要求2. 实验代码及结果2.1 加密2.2 解密2.3整体运行过程 1. 实验要求 设有一段英文文章,为简单起见,仅由26个小写字母、空格、标点符号(引号和逗号)组成,符号集合共29个。现在自定义一...
  • java和javascript加密解密,可相互加密解密,内含javascript代码和java代码,解压即用,自定义密钥

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 20,946
精华内容 8,378
关键字:

自定义加密解密java

java 订阅