當前位置:首頁 » 編程語言 » 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加密,這個是單向加密,不可以解密。要想實現加密和解密,那麼就需要學習密碼學的知識。
希望對你有所幫助。

熱點內容
sql2008錯誤233 發布:2025-07-03 02:28:52 瀏覽:167
創建資料庫語句mysql 發布:2025-07-03 02:14:34 瀏覽:146
python量化投資 發布:2025-07-03 02:05:11 瀏覽:804
proxy代理伺服器地址 發布:2025-07-03 01:56:52 瀏覽:910
ps選區存儲 發布:2025-07-03 01:55:21 瀏覽:842
sql2008連接數 發布:2025-07-03 01:55:20 瀏覽:246
androidstring 發布:2025-07-03 01:53:55 瀏覽:183
密碼sql注入 發布:2025-07-03 00:44:07 瀏覽:555
oa伺服器需要什麼硬體 發布:2025-07-03 00:36:05 瀏覽:512
4mol的naoh怎麼配置 發布:2025-07-03 00:19:10 瀏覽:856