当前位置:首页 » 编程语言 » java加密解密文件

java加密解密文件

发布时间: 2023-01-01 16:41:52

1. java文件加解密

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

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 < c; i++) {

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 < c; i++) {

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 < c; i++) {

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 < c; i++) {

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);

}

lishixin/Article/program/Java/hx/201311/26983

2. 请问用java如何对文件进行加密解密

packagecom.palic.pss.afcs.worldthrough.common.util;

importjavax.crypto.Cipher;
importjavax.crypto.spec.SecretKeySpec;

importrepack.com.thoughtworks.xstream.core.util.Base64Encoder;
/**
*AES加密解密
*@authorEX-CHENQI004
*
*/
publicclassAesUtils{
publicstaticfinalStringcKey="assistant7654321";
/**
*加密--把加密后的byte数组先进行二进制转16进制在进行base64编码
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringencrypt(StringsSrc,StringsKey)throwsException{
if(sKey==null){
("ArgumentsKeyisnull.");
}
if(sKey.length()!=16){
(
"ArgumentsKey'lengthisnot16.");
}
byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);

byte[]encrypted=cipher.doFinal(sSrc.getBytes("UTF-8"));
StringtempStr=parseByte2HexStr(encrypted);

Base64Encoderencoder=newBase64Encoder();
returnencoder.encode(tempStr.getBytes("UTF-8"));
}

/**
*解密--先进行base64解码,在进行16进制转为2进制然后再解码
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringdecrypt(StringsSrc,StringsKey)throwsException{

if(sKey==null){
("499");
}
if(sKey.length()!=16){
("498");
}

byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,skeySpec);

Base64Encoderencoder=newBase64Encoder();
byte[]encrypted1=encoder.decode(sSrc);

StringtempStr=newString(encrypted1,"utf-8");
encrypted1=parseHexStr2Byte(tempStr);
byte[]original=cipher.doFinal(encrypted1);
StringoriginalString=newString(original,"utf-8");
returnoriginalString;
}

/**
*将二进制转换成16进制
*
*@parambuf
*@return
*/
(bytebuf[]){
StringBuffersb=newStringBuffer();
for(inti=0;i<buf.length;i++){
Stringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
returnsb.toString();
}

/**
*将16进制转换为二进制
*
*@paramhexStr
*@return
*/
publicstaticbyte[]parseHexStr2Byte(StringhexStr){
if(hexStr.length()<1)
returnnull;
byte[]result=newbyte[hexStr.length()/2];
for(inti=0;i<hexStr.length()/2;i++){
inthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);
intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),
16);
result[i]=(byte)(high*16+low);
}
returnresult;
}
publicstaticvoidmain(String[]args)throwsException{
/*
*加密用的Key可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定
*/
StringcKey="assistant7654321";
//需要加密的字串
StringcSrc="123456";
//加密
longlStart=System.currentTimeMillis();
StringenString=encrypt(cSrc,cKey);
System.out.println("加密后的字串是:"+enString);
longlUseTime=System.currentTimeMillis()-lStart;
System.out.println("加密耗时:"+lUseTime+"毫秒");
//解密
lStart=System.currentTimeMillis();
StringDeString=decrypt(enString,cKey);
System.out.println("解密后的字串是:"+DeString);
lUseTime=System.currentTimeMillis()-lStart;
System.out.println("解密耗时:"+lUseTime+"毫秒");
}
}

3. 如何利用JAVA对文档进行加密和解密处理,完整的java类

我以前上密码学课写过一个DES加解密的程序,是自己实现的,不是通过调用java库函数,代码有点长,带有用户界面。需要的话联系我

4. 怎么对加密的JAVA class文件进行解密

JAVA class文件加密解密

package com..encrypt;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
public class FileEncryptAndDecrypt {
/**
* 文件file进行加密
* @param fileUrl 文件路径
* @param key 密码
* @throws Exception
*/
public static void encrypt(String fileUrl, String key) throws Exception {
File file = new File(fileUrl);
String path = file.getPath();
if(!file.exists()){
return;
}
int index = path.lastIndexOf("\\");
String destFile = path.substring(0, index)+"\\"+"abc";
File dest = new File(destFile);
InputStream in = new FileInputStream(fileUrl);
OutputStream out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int r;
byte[] buffer2=new byte[1024];
while (( r= in.read(buffer)) > 0) {
for(int i=0;i<r;i++)
{
byte b=buffer[i];
buffer2[i]=b==255?0:++b;
}
out.write(buffer2, 0, r);
out.flush();
}
in.close();
out.close();
file.delete();
dest.renameTo(new File(fileUrl));
appendMethodA(fileUrl, key);
System.out.println("加密成功");
}
/**
*
* @param fileName
* @param content 密钥
*/
public static void appendMethodA(String fileName, String content) {
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
//将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解密
* @param fileUrl 源文件
* @param tempUrl 临时文件
* @param ketLength 密码长度
* @return
* @throws Exception
*/
public static String decrypt(String fileUrl, String tempUrl, int keyLength) throws Exception{
File file = new File(fileUrl);
if (!file.exists()) {
return null;
}
File dest = new File(tempUrl);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
InputStream is = new FileInputStream(fileUrl);
OutputStream out = new FileOutputStream(tempUrl);
byte[] buffer = new byte[1024];
byte[] buffer2=new byte[1024];
byte bMax=(byte)255;
long size = file.length() - keyLength;
int mod = (int) (size%1024);
int div = (int) (size>>10);
int count = mod==0?div:(div+1);
int k = 1, r;
while ((k <= count && ( r = is.read(buffer)) > 0)) {
if(mod != 0 && k==count) {
r = mod;
}
for(int i = 0;i < r;i++)
{
byte b=buffer[i];
buffer2[i]=b==0?bMax:--b;
}
out.write(buffer2, 0, r);
k++;
}
out.close();
is.close();
return tempUrl;
}
/**
* 判断文件是否加密
* @param fileName
* @return
*/
public static String readFileLastByte(String fileName, int keyLength) {
File file = new File(fileName);
if(!file.exists())return null;
StringBuffer str = new StringBuffer();
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
//将写文件指针移到文件尾。
for(int i = keyLength ; i>=1 ; i--){
randomFile.seek(fileLength-i);
str.append((char)randomFile.read());
}
randomFile.close();
return str.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

5. java中如何实现对文件和字符串加密. 解密

DES 密钥生成,加解密方法,,你可以看一下

//DES 密钥生成工具
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

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

public class GenKey {

private static final String DES = "DES";
public static final String SKEY_NAME = "key.des";

public static void genKey1(String path) {

// 密钥
SecretKey skey = null;
// 密钥随机数生成
SecureRandom sr = new SecureRandom();
//生成密钥文件
File file = genFile(path);

try {
// 获取密钥生成实例
KeyGenerator gen = KeyGenerator.getInstance(DES);
// 初始化密钥生成器
gen.init(sr);
// 生成密钥
skey = gen.generateKey();
// System.out.println(skey);

ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* @param file : 生成密钥的路径
* SecretKeyFactory 方式生成des密钥
* */
public static void genKey2(String path) {
// 密钥随机数生成
SecureRandom sr = new SecureRandom();
// byte[] bytes = {11,12,44,99,76,45,1,8};
byte[] bytes = sr.generateSeed(20);
// 密钥
SecretKey skey = null;
//生成密钥文件路径
File file = genFile(path);

try {
//创建deskeyspec对象
DESKeySpec desKeySpec = new DESKeySpec(bytes,9);
//实例化des密钥工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
//生成密钥对象
skey = keyFactory.generateSecret(desKeySpec);
//写出密钥对象
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

private static File genFile(String path) {
String temp = null;
File newFile = null;
if (path.endsWith("/") || path.endsWith("\\")) {
temp = path;
} else {
temp = path + "/";
}

File pathFile = new File(temp);
if (!pathFile.exists())
pathFile.mkdirs();

newFile = new File(temp+SKEY_NAME);

return newFile;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
genKey2("E:/a/aa/");
}

}

//DES加解密方法

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
*制卡文件加/解密 加密方式DES
*/
public class SecUtil {

public static final Log log = LogFactory.getLog(SecUtil.class);

/**
* 解密
*
* @param keyPath
* 密钥路径
* @param source
* 解密前文件
* @param dest
* 解密后文件
*/
public static void decrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
// 读取加密密钥
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
log.info("Error when read keyFile");
throw new RuntimeException(ey1);
} catch (Exception ey2) {
log.info("error when read the keyFile");
throw new RuntimeException(ey2);
}
// 用key产生Cipher
Cipher cipher = null;
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (Exception ey3) {
log.info("Error when create the cipher");
throw new RuntimeException(ey3);
}
// 取得要解密的文件并解密
File file = new File(source);
String filename = file.getName();
try {
// 输出流,请注意文件名称的获取
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(dest));
// 输入流
CipherInputStream in = new CipherInputStream(
new BufferedInputStream(new FileInputStream(file)), cipher);
int thebyte = 0;
while ((thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
} catch (Exception ey5) {
log.info("Error when encrypt the file");
throw new RuntimeException(ey5);
}
}

/**
* 加密
* @param keyPath 密钥路径
* @param source 加密前文件
* @param dest 加密后文件
*/
public static void encrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
// 读取加密密钥
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
log.info("Error when read keyFile");
throw new RuntimeException(ey1);
} catch (Exception ey2) {
log.info("error when read the keyFile");
throw new RuntimeException(ey2);
}
// 用key产生Cipher
Cipher cipher = null;
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (Exception ey3) {
log.info("Error when create the cipher");
throw new RuntimeException(ey3);
}
// 取得要解密的文件并解密
File file = new File(source);
String filename = file.getName();
try {
// 输出流,请注意文件名称的获取
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(dest));
// 输入流
CipherInputStream in = new CipherInputStream(
new BufferedInputStream(new FileInputStream(file)), cipher);
int thebyte = 0;
while ((thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
} catch (Exception ey5) {
log.info("Error when encrypt the file");
throw new RuntimeException(ey5);
}
}

}

6. java简单的文件加密解密

这个应该是作业吧、我还是建议你自己做、而不是在这问了、我们帮你做完、你可以做、等到不会来、在拿出来分享、我们可以共同学习!

7. java 文本文件的加密解密

基本思路简单,
首先用流把文件内容读出来,
然后把内容转成acsii码,
之后移位,可以全文用一种移位,也可以每行或者每个字用一种移位.
最后用流写回去即可.

比如 "我" 这个字的ascii码是\u6211,加1移位成\u6212(戒),这样一片文章就面目全非了.当然移位成什么看你自己的移位算法,然后再转成汉字写回去.

package test;

import java.io.IOException;

public class Native2ascii {

private static final String java_path = "G:\\Java\\jdk 1.6";//你的jdk的绝对路径
private static final String target_file = "C:\\a.txt"; //原始文本的完整路径
private static final String result_file = "C:\\b.txt";//转码后的路径
private static final String back_file = "C:\\c.txt";//转回的路径
private static final String encoding = "GBK";// 编码

public static void native2ascii()
{
try {
Runtime.getRuntime().exec(java_path+"\\bin\\native2ascii.exe -encoding "+encoding+" "+target_file+" "+result_file);
//读取b.txt中的内容进行移位,我的没有移位所以写回c.txt中还能够看懂.
Runtime.getRuntime().exec(java_path+"\\bin\\native2ascii.exe -reverse "+result_file+" "+back_file);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String arg[]){
native2ascii();
}

}

8. 如何用java实现加密与解密

通常比较简单的加密方法就是你把文本文件加载读取以后,得到的每一个char加上一个固定的整数,然后再保存,这样内容就看不懂了。
再读取以后,把每一个char减去固定的整数,然后保存,就还原回来了。
这种方法是最最简单的加密方式,不需要使用任何的加密算法。

9. java中如何实现对文件和字符串加密. 解密

你好,加密的方式有很多中,如传统加密,后期的分组加密,序列流加密,这些是对称加密,现在有着名的非对称加密。
java的扩展包很好的实现了你需要的功能。这个包在java.security.*;当然了还有很多好的加密方法,在sun的第三方jar包中有。目前密码加密使用用的是MD5加密,这个是单向加密,不可以解密。要想实现加密和解密,那么就需要学习密码学的知识。
希望对你有所帮助。

热点内容
随机启动脚本 发布:2025-07-05 16:10:30 浏览:513
微博数据库设计 发布:2025-07-05 15:30:55 浏览:18
linux485 发布:2025-07-05 14:38:28 浏览:298
php用的软件 发布:2025-07-05 14:06:22 浏览:747
没有权限访问计算机 发布:2025-07-05 13:29:11 浏览:421
javaweb开发教程视频教程 发布:2025-07-05 13:24:41 浏览:675
康师傅控流脚本破解 发布:2025-07-05 13:17:27 浏览:229
java的开发流程 发布:2025-07-05 12:45:11 浏览:673
怎么看内存卡配置 发布:2025-07-05 12:29:19 浏览:274
访问学者英文个人简历 发布:2025-07-05 12:29:17 浏览:824