Java文件加解密

Java文件加解密,第1张

做网站有时会处理一些上传下载的文件 可能会用到加解颤此密功能 以下是一个加解密方法

Java代码

import java io File

import java io FileInputStream

import java io FileOutputStream

import java io IOException

import nf Conf

import mon time TimeHandler

/**

* 加解密单元

* @author lupingui

* : :

*/

public class EncryptDecrypt {

//加解密KEY 这个不能变动 这里可以由任意的字符组成 尽量用特殊字符

static final byte[] KEYVALUE = getBytes()

//读取字节的长度

static final int BUFFERLEN =

//加密临时存储目录

static final String TRANSIT_DIR_ENC =

//解密临时存储目录

static final String TRANSIT_DIR_DEC =

/**

* 文件加密

* @param oldFile 待加密文件

* @param saveFileName 加密后文件保存路径

* @return

* @throws IOException

*/

public static boolean encryptFile(File oldFile String saveFileName) throws IOException{

//如果传入的文件不存在或者不是文件则直接返回

老誉if (!oldFile exists() || !oldFile isFile()){

return false

}

FileInputStream in = new FileInputStream(oldFile)

//加密后存储的文件茄含迅

File file = new File(saveFileName)

if (!file exists()){

return false

}

//读取待加密文件加密后写入加密存储文件中

FileOutputStream out = new FileOutputStream(file)

int c pos keylen

pos =

keylen = KEYVALUE length

byte buffer[] = new byte[BUFFERLEN]

while ((c = in read(buffer)) != ) {

for (int i = i <ci++) {

buffer[i] ^= KEYVALUE[pos]

out write(buffer[i])

pos++

if (pos == keylen){

pos =

}

}

}

in close()

out close()

return true

}

/**

* 文件加密

* @param oldFile:待加密文件

* @param saveFile 加密后的文件

* @return

* @throws IOException

*/

public static boolean encryptFile(File oldFile File saveFile) throws IOException{

//如果传入的文件不存在或者不是文件则直接返回

if (!oldFile exists() || !oldFile isFile() || !saveFile exists() || !saveFile isFile()){

return false

}

FileInputStream in = new FileInputStream(oldFile)

//读取待加密文件加密后写入加密存储文件中

FileOutputStream out = new FileOutputStream(saveFile)

int c pos keylen

pos =

keylen = KEYVALUE length

byte buffer[] = new byte[BUFFERLEN]

while ((c = in read(buffer)) != ) {

for (int i = i <ci++) {

buffer[i] ^= KEYVALUE[pos]

out write(buffer[i])

pos++

if (pos == keylen){

pos =

}

}

}

in close()

out close()

return true

}

/**

* 文件加密

* @param oldFile 待加密文件

* @return

* @throws IOException

*/

public static File encryptFile(File oldFile) throws IOException{

//如果传入的文件不存在或者不是文件则直接返回

if (!oldFile exists() || !oldFile isFile()){

return null

}

FileInputStream in = new FileInputStream(oldFile)

//临时加密文件存储目录

File dirFile = new File(TRANSIT_DIR_ENC)

//如果临时存储目录不存在或不是目录则直接返回

if (!dirFile exists() || !dirFile isDirectory()){

return null

}

//加密后存储的文件

File file = new File(dirFile enc_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName())

if (!file exists()){

file createNewFile()

}

//读取待加密文件加密后写入加密存储文件中

FileOutputStream out = new FileOutputStream(file)

int c pos keylen

pos =

keylen = KEYVALUE length

byte buffer[] = new byte[BUFFERLEN]

while ((c = in read(buffer)) != ) {

for (int i = i <ci++) {

buffer[i] ^= KEYVALUE[pos]

out write(buffer[i])

pos++

if (pos == keylen){

pos =

}

}

}

in close()

out close()

//返回加密后的文件

return file

}

/**

* 文件加密

* @param oldFileName 待加密文件路径

* @return

* @throws IOException

* @throws Exception

*/

public static File encryptFile(String oldFileName) throws IOException {

//如果待加密文件路径不正确则直接返回

if (oldFileName == null || oldFileName trim() equals( )){

return null

}

//待加密文件

File oldFile = new File(oldFileName)

//如果传入的文件不存在或者不是文件则直接返回

if (!oldFile exists() || !oldFile isFile()){

return null

}

//调用文件加密方法并返回结果

return encryptFile(oldFile)

}

/**

* 文件解密

* @param oldFile 待解密文件

* @return

* @throws IOException

*/

public static File decryptFile(File oldFile) throws IOException{

//如果待解密文件不存在或者不是文件则直接返回

if (!oldFile exists() || !oldFile isFile()){

return null

}

FileInputStream in = new FileInputStream(oldFile)

//临时解密文件存储目录

File dirFile = new File(TRANSIT_DIR_DEC)

//如果临时解密文件存储目录不存在或不是目录则返回

if (!dirFile exists() || !dirFile isDirectory()){

return null

}

//解密存储文件

File file = new File(dirFile dec_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName() substring(oldFile getName() lastIndexOf( )))

if (!file exists()){

file createNewFile()

}

//读取待解密文件并进行解密存储

FileOutputStream out = new FileOutputStream(file)

int c pos keylen

pos =

keylen = KEYVALUE length

byte buffer[] = new byte[BUFFERLEN]

while ((c = in read(buffer)) != ) {

for (int i = i <ci++) {

buffer[i] ^= KEYVALUE[pos]

out write(buffer[i])

pos++

if (pos == keylen){

pos =

}

}

}

in close()

out close()

//返回解密结果文件

return file

}

/**

* 文件解密

* @param oldFileName 待解密文件路径

* @return

* @throws Exception

*/

public static File decryptFile(String oldFileName) throws Exception {

//如果待解密文件路径不正确则直接返回

if (oldFileName == null || oldFileName trim() equals( )){

return null

}

//待解密文件

File oldFile = new File(oldFileName)

//如果待解密文件不存在或不是文件则直接返回

if (!oldFile exists() || !oldFile isFile()){

return null

}

//调用文件解密方法并返回结果

return decryptFile(oldFile)

}

lishixinzhi/Article/program/Java/hx/201311/26983

问 如果我把我的class文件加密 在运行时用指定的类加载器(class loader)装入并解密它 这样子能防止被反编译吗? 答 防止JAVA字节码反编译这个问题在java语言雏形期就有了 尽管市面上存在一些反编译的工具可以利用 但是JAVA程序员还是不断的努力寻找新的更有效的方法来保护他们的智慧结晶 在此 我将详细给大家解释这一直来在论坛上有争议的话题 Class文件能被很轻松的重构生成JAVA源文件与最初JAVA字节码的设计目的和商业交易有紧密地联系 另外 JAVA字节码被设计成简洁 平台独立性 网络灵活性 并且易于被字节码解释器和JIT (just in time)/HotSpot 编译器所分析 可以清楚地了解程序员的目的 Class文件要比JAVA源文件更易于分析 如配差指果不能阻止被反编译的话 至少可以通过一些方法来增加它的困难性 例如: 在庆绝一个分步编译里 你可以打乱Class文件的数据以使其难读或者难以被反编译成正确的JAVA源文件 前者可以采用极端函数重载 后者用 *** 作控制流建立控制结构使其难以恢复正常次序 有更多成功的商业困惑者采用这些或其他的技术来保护自己的代码 不幸的是 哪种方法都必须改变JVM运行的代码 并且许多用户害怕这种转化会给他们的程序带来新的Bug 而且 方法和字段重命名会调用反射从而使程序停止工作 改变类和包的名字会破坏其他的JAVA APIS(JNDI URL providers etc) 除了改变名字 如果字节码偏移量和源代码行数之间的关系改变了 在恢复这有异常的堆栈将很困难 于是就有了一些打乱JAVA源代码的选项 但是这将从本质上导致一系列问题的产生 加密而不打乱 或许上述可能会使你问 假如我把字节码加密而不是处理字节码 并且JVM运行时自动将它解密并装入类加载器 然后JVM运行解密后的字节码文件 这样就不会被反编译了对吗?考虑到你是第一个提出这种想法的并且它又能正常运行 我表示遗憾和不幸 这种想法是错误的 下面是一个简单的类编码器 为了阐明这种思想 我采用了一个实例和一个很通用的类加载器来运行它 该程序包括两个类 public class Main{public static void main (final String [] args){  System out println ( secret result = + MySecretClass mySecretAlgorithm ())}} // End of classpackage deimport java util Randompublic class MySecretClass{/** * Guess what the secret algorithm just uses a random number generator */public static int mySecretAlgorithm (){return (int) s_random nextInt ()}private static final Random s_random = new Random (System currentTimeMillis ())} // End of class我想通过加密相关的培配class文件并在运行期解密来隐藏de MySecretClass的执行 用下面这个工具可以达到效果(你可以到这里下载Resources) public class EncryptedClassLoader extends URLClassLoader{public static void main (final String [] args)throws Exception{if ( run equals (args [ ]) &&(args length >=  )){// Create a custom loader that will use the current loader as// delegation parent:final ClassLoader appLoader =new EncryptedClassLoader (EncryptedClassLoader class getClassLoader () new File (args [ ]))// Thread context loader must be adjusted as well:Thread currentThread () setContextClassLoader (appLoader)final Class app = appLoader loadClass (args [ ])final Method appmain = app getMethod ( main new Class [] {String [] class})final String [] appargs = new String [args length ]System arraycopy (args appargs appargs length)appmain invoke (null new Object [] {appargs})}else if ( encrypt equals (args [ ]) &&(args length >= )){ encrypt specified classes }elsethrow new IllegalArgumentException (USAGE)}/** * Overrides java lang ClassLoader loadClass() to change the usual parent child * delegation rules just enough to be able to snatch application classes * from under system classloader s nose */public Class loadClass (final String name final boolean resolve)throws ClassNotFoundException{if (TRACE) System out println ( loadClass ( + name + + resolve + ) )Class c = null// First check if this class has already been defined by this classloader// instance:c = findLoadedClass (name)if (c == null){Class parentsVersion = nulltry{// This is slightly unorthodox: do a trial load via the// parent loader and note whether the parent delegated or not// what this acplishes is proper delegation for all core// and extension classes without my having to filter on class name: parentsVersion = getParent () loadClass (name)if (parentsVersion getClassLoader () != getParent ())c = parentsVersion}catch (ClassNotFoundException ignore) {}catch (ClassFormatError ignore) {}if (c == null){try{// OK either c was loaded by the system (not the bootstrap// or extension) loader (in which case I want to ignore that// definition) or the parent failed altogethereither way I// attempt to define my own version:c = findClass (name)}catch (ClassNotFoundException ignore){// If that failed fall back on the parent s version// [which could be null at this point]:c = parentsVersion}}}if (c == null)throw new ClassNotFoundException (name)if (resolve)resolveClass (c)return c}/** * Overrides java new URLClassLoader defineClass() to be able to call * crypt() before defining a class */protected Class findClass (final String name)throws ClassNotFoundException{if (TRACE) System out println ( findClass ( + name + ) )// class files are not guaranteed to be loadable as resources// but if Sun s code does it so perhaps can mine final String classResource = name replace ( / ) + class final URL classURL = getResource (classResource)if (classURL == null)throw new ClassNotFoundException (name)else{InputStream in = nulltry{in = classURL openStream ()final byte [] classBytes = readFully (in)lishixinzhi/Article/program/Java/hx/201311/25555


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12310904.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存