修改spring源碼重寫classloader實現項目加密

 

(一)操做方法和spring源碼添加修改部分java

事先說明:spring源碼要下載好,會有修改spring的源碼操做,本文和本做者所依賴的spring項目的版本是3.1.1,spring4及以上源碼對應的類路徑可能有所改變,須要本身找到要修改的類哦,類名應該是不會變的。望理解~~web

操做步驟: ~具體說明看類文件註釋~算法

1.運行ProduceKey.java的main方法 生成 key.key文件spring

2.ClassesEncryption類中,修改項目路徑,修改key文件路徑apache

3.執行ClassesEncryption的main方法加密文件windows

4.將OverrideClassLoader項目生成jar包,放在tomcat/lib下(本身網上看操做)數組

5.在tomcat/conf/context.xml 中Context 節點中添加
  <Loader loaderClass="com.loader.ReBuildClassLoader" delegate="false"></Loader>
tomcat

6. 替換tomcat的文件,好比com/ 下的除了(com/webapp/entity)下全部文件app

7.啓動tomcatdom

 

加密修改spring 源碼

1.org.springframework.context-3.1.1.RELEASE.jar
2.org.springframework.core-3.1.1.RELEASE.jar

 

其中org.springframework.context-3.1.1.RELEASE.jar 修改類

(1)ClassPathScanningCandidateComponentProvider.java

line:230 加入
packageSearchPath = packageSearchPath.replace(".class", ".zdywjmjw");
System.out.println("packageSearchPath"+packageSearchPath);
Resource[] resourcesZdywjmjw = this.resourcePatternResolver.getResources(packageSearchPath);
Resource[] resources = new Resource[resourcesClass.length+resourcesZdywjmjw.length];
System.arraycopy(resourcesClass, 0, resources, 0, resourcesClass.length); 
System.arraycopy(resourcesZdywjmjw, 0, resources, resourcesClass.length, resourcesZdywjmjw.length);

 

其中org.springframework.core-3.1.1.RELEASE.jar 修改類

(1)ClassPathResource.java

在類下面添加下列方法

private static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}

// 把文件讀入byte數組
private byte[] readFile(String filename) throws IOException {
File file = new File(filename);
long len = file.length();
byte data[] = new byte[(int) len];
FileInputStream fin = new FileInputStream(file);
int r = fin.read(data);
if (r != len)
throw new IOException("Only read " + r + " of " + len + " for " + file);
fin.close();
return data;
}

// 把byte數組寫出到文件
private void writeFile(String filename, byte data[]) throws IOException {
FileOutputStream fout = new FileOutputStream(filename);
fout.write(data);
fout.close();
}

 

line 168行 修改
String basepath =this.getClass().getResource("/").getPath();
if(isWindowsOS()){
basepath = basepath.substring(1,basepath.length());//window下增長
}
String reloadedClass = basepath+this.path.replace(".class", ".zdywjmjw");
File file = new File(reloadedClass);
if (file.exists()) {
// 下面是定製部分
  try {
    String keyFilename = basepath+"key.key";
    // 讀取密匙
    String algorithm = "DES";
    byte rawKey[] = readFile(keyFilename);
    DESKeySpec dks = new DESKeySpec(rawKey);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
    SecretKey key = keyFactory.generateSecret(dks);
    SecureRandom sr = new SecureRandom();
    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, key, sr);
    // 讀取通過加密的類文件
    byte classData[] = readFile(pclass);
    if (classData != null) {
      byte decryptedClassData[] = cipher.doFinal(classData); // 解密
      InputStream sbs = new ByteArrayInputStream(decryptedClassData); 
      return sbs;
    }
  } catch (Exception fnfe) {

  }
}

 

(2).SimpleMetadataReader.java

 

添加方法
private static boolean isWindowsOS() {
  boolean isWindowsOS = false;
  String osName = System.getProperty("os.name");
  if (osName.toLowerCase().indexOf("windows") > -1) {
    isWindowsOS = true;
  }
  return isWindowsOS;
}

public static byte[] readFile(String filename) throws IOException {
  File file = new File(filename);
  long len = file.length();
  byte data[] = new byte[(int) len];
  FileInputStream fin = new FileInputStream(file);
  int r = fin.read(data);
  if (r != len)
  throw new IOException("Only read " + r + " of " + len + " for " + file);
  fin.close();
  return data;
}

 

修改構造類

SimpleMetadataReader(Resource resource, ClassLoader classLoader) throws IOException {
  InputStream is = resource.getInputStream();
  ClassReader classReader = null;
  try {
    String filename = ""; 
    if (resource.getURI().toString().indexOf("jar:file") == -1 ) {
      String checkPath="";
      if(isWindowsOS()){
      checkPath = "classes\\com";
    }else{
      checkPath = "classes/com";
    }
    if(resource.getFile().getAbsolutePath().indexOf(checkPath)!=-1){
      filename = resource.getFile().getAbsolutePath().replace(".class", ".zdywjmjw"); 
      File file = new File(filename);
      if(file.exists()){
      //進行解密
      String basepath =this.getClass().getResource("/").getPath();
      if(isWindowsOS()){
        basepath = basepath.substring(1,basepath.length());
      }
      String keyFilename = basepath+"key.key";
      String algorithm = "DES";
      try{
        // 生成密匙
        SecureRandom sr = new SecureRandom();
        byte rawKey[] = readFile(keyFilename);
        DESKeySpec dks = new DESKeySpec(rawKey);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        SecretKey key = keyFactory.generateSecret(dks);

        // 建立用於實際加密操做的Cipher對象
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, sr);
        byte classData[] = readFile(name);
        byte decryptedClassData[] = cipher.doFinal(classData);
        classReader = new ClassReader(decryptedClassData);
      } catch(NoSuchAlgorithmException e){
        e.printStackTrace();
      } catch (InvalidKeyException e) {
        e.printStackTrace();
      } catch (InvalidKeySpecException e) {
        e.printStackTrace();
      } catch (NoSuchPaddingException e) {
        e.printStackTrace();
      } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
      } catch (BadPaddingException e) {
        e.printStackTrace();
      }
    }else{
      classReader = new ClassReader(is);
    }
   }else{
    classReader = new ClassReader(is);
   }
  }else{
    classReader = new ClassReader(is);
  }
  }finally {
    is.close();
  }

  AnnotationMetadataReadingVisitor visitor = new AnnotationMetadataReadingVisitor(classLoader);
  classReader.accept(visitor, true);

  this.annotationMetadata = visitor;
  // (since AnnotationMetadataReader extends ClassMetadataReadingVisitor)
  this.classMetadata = visitor;
  this.resource = resource;
}

 

 

(3)LocalVariableTableParameterNameDiscoverer.java

line 103 行修改
String cName = clazz.getResource("/").getPath()+clazz.getName().replace(".", "/")+".class";
is = clazz.getClassLoader().getResourceAsStream(cName);
if(is == null){
  // We couldn't load the class file, which is not fatal as it
  // simply means this method of discovering parameter names won't work.
  if (logger.isDebugEnabled()) {
    logger.debug("Cannot find '.class' file for class [" + clazz
    + "] - unable to determine constructors/methods parameter names");
  }
  return NO_DEBUG_INFO_MAP;
}

 

 

(二)項目相關

項目名稱:OverrideClassLoader

項目打包方式:jar,是普通Java工程

項目結構:

com.key

com.loader

com.util

其中 key包下面文件有:ClassesEncryption.java、ProduceKey.java、GenerateEncryptedClassMain

loader包下面有文件:ReBuildClassLoader.java 

util包下面有文件:FileUtil.java

 

 

(1)ProduceKey.java

 

package com.key;

import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import com.util.FileUtil;
/**
* 生成key文件類
* @author win7
*
*/
public class ProduceKey {

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

    String keyFilename = null;
    boolean windowsOS = isWindowsOS();//檢查是不是window系統
    System.out.println(windowsOS);
    if (windowsOS) {
      keyFilename = "D://developer/apache-tomcat7/webapps/項目名稱/WEB-INF/classes/key.key";//是本地開發的項目,tomcat的路徑
    } else {
      keyFilename = "/usr/local/tomcat/webapps/項目名稱/WEB-INF/classes/key.key";
    }

    String algorithm = "DES";

    // 生成密匙
    SecureRandom sr = new SecureRandom();
    KeyGenerator kg = KeyGenerator.getInstance(algorithm);
    kg.init(sr);
    SecretKey key = kg.generateKey();

    // 把密匙數據保存到文件,放入指定位置
    FileUtil.writeFile(keyFilename, key.getEncoded());
  }

  private static boolean isWindowsOS() {
    boolean isWindowsOS = false;
    String osName = System.getProperty("os.name");
    if (osName.toLowerCase().indexOf("windows") > -1) {
      isWindowsOS = true;
    }
    return isWindowsOS;
  }

}

 

 

(2)ClassesEncryption.java

 

package com.key;

import java.io.File;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import com.util.FileUtil;
/**
* class文件加密類
* @author win7
*
*/
public class ClassesEncryption {
  public static List<File> filelist = new ArrayList<>();

  public static void main(String[] args) throws Exception {
  System.out.println("search start");

  // 獲得要加密的項目下com目錄下的class文件
  getFileList("D://developer/apache-tomcat7/webapps/項目名稱/WEB-INF/classes/com");

  System.out.println("文件數量" + filelist.size());

  // 獲取文件名祕鑰
  String keyFilename = "D://developer/apache-tomcat7/webapps/項目名稱/WEB-INF/classes/key.key";
  // 算法
  String algorithm = "DES";

  // -------下面開始生成密匙-------
  // 強加密隨機數生成器
  SecureRandom sr = new SecureRandom();
  // 將加密後的key.key轉成字節數組
  byte rawKey[] = FileUtil.readFile(keyFilename);
  // 建立一個 DESKeySpec 對象,使用 rawKey 中的前 8 個字節做爲 DES 密鑰的密鑰內容。
  DESKeySpec dks = new DESKeySpec(rawKey);
  // 獲得轉換指定算法的祕密密鑰的SecretKeyFactory對象。
  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
  // 根據提供的密鑰規範(密鑰材料)生成 SecretKey 對象
  SecretKey key = keyFactory.generateSecret(dks);

  // 建立用於實際加密操做的Cipher對象 , Cipher:此類爲加密和解密提供密碼功能
  Cipher ecipher = Cipher.getInstance(algorithm);
  // 參數:加密的常量,加密密鑰, 算法參數
  ecipher.init(Cipher.ENCRYPT_MODE, key, sr);

    // 加密命令行中指定的每個類
    for (int i = 0; i < filelist.size(); i++) {
      String filename = filelist.get(i).getAbsolutePath();
      byte classData[] = FileUtil.readFile(filename); // 讀入類文件
      byte encryptedClassData[] = ecipher.doFinal(classData); // 加密
      String projectFile = filename.replace(".class", ".zdywjmjw");//zdyljzq:自定義文件名結尾
      FileUtil.writeFile(projectFile, encryptedClassData); // 保存加密後的內容
      System.out.println("Encrypted " + projectFile);

      File classFile = new File(filename);
      classFile.delete();
    }
  }

  public static void encrypt(String tomcat_home) throws Exception {
    System.out.println("search start");
    getFileList(tomcat_home + "webapps/項目名稱/WEB-INF/classes/com");

    System.out.println("文件數量" + filelist.size());

    String keyFilename = tomcat_home + "webapps/項目名稱/WEB-INF/classes/key.key";
    String algorithm = "DES";// 算法

    // -------下面開始生成密匙-------
    // 強加密隨機數生成器
    SecureRandom sr = new SecureRandom();
    // 將加密後的key.key轉成字節數組
    byte rawKey[] = FileUtil.readFile(keyFilename);
    // 建立一個 DESKeySpec 對象,使用 rawKey 中的前 8 個字節做爲 DES 密鑰的密鑰內容。
    DESKeySpec dks = new DESKeySpec(rawKey);
    // 獲得轉換指定算法的祕密密鑰的SecretKeyFactory對象。
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
    // 根據提供的密鑰規範(密鑰材料)生成 SecretKey 對象
    SecretKey key = keyFactory.generateSecret(dks);

    // 建立用於實際加密操做的Cipher對象 , Cipher:此類爲加密和解密提供密碼功能
    Cipher ecipher = Cipher.getInstance(algorithm);
    // 參數:加密的常量,加密密鑰, 算法參數
    ecipher.init(Cipher.ENCRYPT_MODE, key, sr);

    // 加密命令行中指定的每個類
    for (int i = 0; i < filelist.size(); i++) {
      String filename = filelist.get(i).getAbsolutePath();
      byte classData[] = FileUtil.readFile(filename); // 讀入類文件
      byte encryptedClassData[] = ecipher.doFinal(classData); // 加密
      String projectFile = filename.replace(".class", ".zdywjmjw");//zdyljzq:自定義文件名結尾
      FileUtil.writeFile(projectFile, encryptedClassData); // 保存加密後的內容
      System.out.println("Encrypted " + projectFile);

      File classFile = new File(filename);
      classFile.delete();

    }
  }

/**
* 注意:加密的時候不能加密實體,要否則項目就啓動不成功或者異常
* @param strPath
* @return
*/
   public static List<File> getFileList(String strPath) {
      File dir = new File(strPath);
      File[] files = dir.listFiles(); // 該文件目錄下文件所有放入數組
      if (files != null) {
        for (int i = 0; i < files.length; i++) {
          String fileName = files[i].getName();
          if (files[i].isDirectory()) { // 判斷是文件仍是文件夾
            getFileList(files[i].getAbsolutePath()); // 獲取文件絕對路徑
          } else if (fileName.endsWith(".class")) { // 判斷文件名是否以.class結尾
            String strFileName = files[i].getAbsolutePath();
            // System.out.println("---" + strFileName);
            if (isWindowsOS()) {
              if (strFileName.indexOf("com\\項目名稱\\webapp\\entity") == -1) {
                filelist.add(files[i]);
              }
            } else {
              if (strFileName.indexOf("com/項目名稱/webapp/entity") == -1) {
              filelist.add(files[i]);
            }
          }

          } else {
          continue;
        }
      }

    }
    return filelist;
  }

  public static boolean isWindowsOS() {
    boolean isWindowsOS = false;
    String osName = System.getProperty("os.name");
    if (osName.toLowerCase().indexOf("windows") > -1) {
      isWindowsOS = true;
    }
    return isWindowsOS;
  }
}

 

 

(3)GenerateEncryptedClassMain.java

 

package com.key;

import java.util.Scanner;
/**
* main方法生成加密class文件
* @author win7
*
*/
public class GenerateEncryptedClassMain {
  public static void main(String[] args) {
    try {
      Scanner s = new Scanner(System.in);
      String str = null;
      System.out.println("請tomcat路徑以'/'結尾:");//如: /usr/local/tomcat/
      str = s.next();
      if (str == null || str.trim().equals("")) {
        System.out.println("tomcat路徑不能爲空");
        return;
      }
      String tomcat_home = str;
      ClassesEncryption.encrypt(tomcat_home);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

 

 

(4)ReBuildClassLoader.java

 

package com.loader;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.catalina.loader.WebappClassLoader;

import com.util.FileUtil;

/**
* 自定義類加載器
* WebappClassLoader:是tomcat的jar包提供,因此要添加 tomcat server Runtime
* 
* @author win7
*
*/
public class ReBuildClassLoader extends WebappClassLoader {
  // 這些對象在構造函數中設置,之後loadClass()方法將利用它們解密類
  private SecretKey key;
  private Cipher cipher;

  public ReBuildClassLoader() {
    super();
  }

  public ReBuildClassLoader(ClassLoader parent) {
    super(parent);
  }

  @Override
  public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    try {
      // 要建立的Class對象
      Class clasz = null;

      // 必需的步驟1:若是類已經在系統緩衝之中,沒必要再次裝入它
      clasz = findLoadedClass(name);

      if (clasz != null)
        return clasz;

        // 下面是定製部分
      try {
        String basepath = "";
        if (isWindowsOS()) {
          basepath = "D://developer/apache-tomcat7/webapps/項目名稱/WEB-INF/classes/";// 項目物理地址
        } else {
          basepath = "/usr/local/tomcat/webapps/項目名稱/WEB-INF/classes/";
        }
        String cname = basepath + name.replace('.', '/') + ".zdywjmjw";
        File file = new File(cname);
        if (file.exists()) {
          String keyFilename = basepath + "key.key";
          // 讀取密匙
          String algorithm = "DES";
          // System.err.println("[DecryptStart: reading key]");
          byte rawKey[] = FileUtil.readFile(keyFilename);
          DESKeySpec dks = new DESKeySpec(rawKey);
          SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
          key = keyFactory.generateSecret(dks);
          SecureRandom sr = new SecureRandom();
          // System.err.println("[DecryptStart: creating cipher]");
          cipher = Cipher.getInstance(algorithm);
          cipher.init(Cipher.DECRYPT_MODE, key, sr);
          // 讀取通過加密的類文件
          byte classData[] = FileUtil.readFile(cname);
          if (classData != null) {
            byte decryptedClassData[] = cipher.doFinal(classData); // 解密
            clasz = defineClass(name, decryptedClassData, 0, decryptedClassData.length); // 再把它轉換成一個類
            // System.err.println("[DecryptStart: decrypting class + name + "]");
          }
        }
      } catch (FileNotFoundException fnfe) {

      }

      // 必需的步驟2:若是上面沒有成功
      // 嘗試用默認的ClassLoader裝入它
      if (clasz == null)
        return super.loadClass(name, resolve);

        // 必需的步驟3:若有必要,則裝入相關的類
        if (resolve && clasz != null)
          resolveClass(clasz);

          return clasz;// 把類返回給調用者

        } catch (IOException ie) {
          throw new ClassNotFoundException(ie.toString());
        } catch (GeneralSecurityException gse) {
          throw new ClassNotFoundException(gse.toString());
        }
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
      return super.loadClass(name);
    }

    @Override
    public InputStream getResourceAsStream(String arg0) {
      String pclass = arg0.replace(".class", ".zdywjmjw");
      File file = new File(pclass);
      if (file.exists()) {
      // 下面是定製部分
      try {
        String basepath = "";
        if (isWindowsOS()) {
          basepath = "D://developer/apache-tomcat7/webapps/項目名稱/WEB-INF/classes/";// 項目物理地址
        } else {
          basepath = "/usr/local/tomcat/webapps/項目名稱/WEB-INF/classes/";
        }
        String keyFilename = basepath + "key.key";
        // 讀取密匙
        String algorithm = "DES";
        byte rawKey[] = FileUtil.readFile(keyFilename);
        DESKeySpec dks = new DESKeySpec(rawKey);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        key = keyFactory.generateSecret(dks);
        SecureRandom sr = new SecureRandom();
        cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, sr);
        // 讀取通過加密的類文件
        byte classData[] = FileUtil.readFile(pclass);
        if (classData != null) {
          byte decryptedClassData[] = cipher.doFinal(classData); // 解密
          InputStream sbs = new ByteArrayInputStream(decryptedClassData);
          return sbs;
          }
        } catch (Exception fnfe) {

        }
      }
      return super.getResourceAsStream(arg0);
    }

  private boolean isWindowsOS() {
    boolean isWindowsOS = false;
    String osName = System.getProperty("os.name");
    if (osName.toLowerCase().indexOf("windows") > -1) {
      isWindowsOS = true;
    }
      return isWindowsOS;
    }

  }

 

 

FileUtil.java

 

package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {
  // 把文件讀入byte數組
  static public byte[] readFile(String filename) throws IOException {
  File file = new File(filename);
  long len = file.length();
  byte data[] = new byte[(int) len];
  FileInputStream fin = new FileInputStream(file);
  int r = fin.read(data);
  if (r != len)
    throw new IOException("Only read " + r + " of " + len + " for " + file);
    fin.close();
    return data;
  }

  // 把byte數組寫出到文件  static public void writeFile(String filename, byte data[]) throws IOException {    FileOutputStream fout = new FileOutputStream(filename);    fout.write(data);    fout.close();  }}

相關文章
相關標籤/搜索