Created
September 2, 2012 02:09
-
-
Save jsfeng/3593868 to your computer and use it in GitHub Desktop.
CryptoClassLoader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This class loader loads encrypted class files. | |
*/ | |
class CryptoClassLoader extends ClassLoader | |
{ | |
/** | |
* Constructs a crypto class loader. | |
* @param k the decryption key | |
*/ | |
public CryptoClassLoader(int k) | |
{ | |
key = k; | |
} | |
protected Class<?> findClass(String name) throws ClassNotFoundException | |
{ | |
byte[] classBytes = null; | |
try | |
{ | |
classBytes = loadClassBytes(name); | |
} | |
catch (IOException e) | |
{ | |
throw new ClassNotFoundException(name); | |
} | |
Class<?> cl = defineClass(name, classBytes, 0, classBytes.length); | |
if (cl == null) throw new ClassNotFoundException(name); | |
return cl; | |
} | |
/** | |
* Loads and decrypt the class file bytes. | |
* @param name the class name | |
* @return an array with the class file bytes | |
*/ | |
private byte[] loadClassBytes(String name) throws IOException | |
{ | |
String cname = name.replace('.', '/') + ".caesar"; | |
FileInputStream in = null; | |
in = new FileInputStream(cname); | |
try | |
{ | |
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); | |
int ch; | |
while ((ch = in.read()) != -1) | |
{ | |
byte b = (byte) (ch - key); | |
buffer.write(b); | |
} | |
in.close(); | |
return buffer.toByteArray(); | |
} | |
finally | |
{ | |
in.close(); | |
} | |
} | |
private int key; | |
} | |
Listing 9-2. Caesar.java | |
import java.io.*; | |
/** | |
* Encrypts a file using the Caesar cipher. | |
* @version 1.00 1997-09-10 | |
* @author Cay Horstmann | |
*/ | |
public class Caesar | |
{ | |
public static void main(String[] args) | |
{ | |
if (args.length != 3) | |
{ | |
System.out.println("USAGE: java Caesar in out key"); | |
return; | |
} | |
try | |
{ | |
FileInputStream in = new FileInputStream(args[0]); | |
FileOutputStream out = new FileOutputStream(args[1]); | |
int key = Integer.parseInt(args[2]); | |
int ch; | |
while ((ch = in.read()) != -1) | |
{ | |
byte c = (byte) (ch + key); | |
out.write(c); | |
} | |
in.close(); | |
out.close(); | |
} | |
catch (IOException exception) | |
{ | |
exception.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment