思路:文件加密,簡(jiǎn)單來說就是把文件讀取出來,把讀取出來的字節(jié)碼數(shù)組進(jìn)行遍歷,把每一個(gè)碼值和一個(gè)秘鑰(隨便一個(gè)數(shù))進(jìn)行異或運(yùn)算,將運(yùn)算后的結(jié)果全部寫入到文件里。因?yàn)槲募拇a值全都做了改變,文件自然就無法打開了,這是加密過程。解密過程就是再執(zhí)行一次,因?yàn)?strong>數(shù)字對(duì)另一個(gè)數(shù)進(jìn)行兩次異或運(yùn)算等于數(shù)字本身。再異或一次碼值就恢復(fù)原樣了,文件自然也就可以恢復(fù)原樣。
文件加密
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 文件加密
*/
public class FileEncrypt {
public static void main(String[] args) throws IOException {
// 需要加密/解密的文件路徑
String inputPath = "out.txt";
// 加密/解密后的文件路徑
String outPath = "input.txt";
// 用于存儲(chǔ)文件字節(jié)碼的集合數(shù)組
List<Byte> byteList = new ArrayList<>();
// 秘鑰
Byte key = 17;
// 讀取文件
readFile(inputPath, byteList);
// 加密/解密
encryption(byteList, key);
// 生成加密/解密后的文件
writeText(byteList, outPath);
}
/**
* 讀取文件
*
* @param inputPath 文件輸入路徑
* @param byteList 文件的字節(jié)碼列表
* @throws IOException
*/
public static void readFile(String inputPath, List<Byte> byteList) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputPath));
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
for (int i = 0; i < len; i++) {
byteList.add(bytes[i]);
}
}
bis.close();
}
/**
* 加密/解密
*
* @param byteList
* @param key
*/
public static void encryption(List<Byte> byteList, byte key) {
for (int i = 0; i < byteList.size(); i++) {
Byte aByte = byteList.get(i);
// 把集合中的字節(jié)碼與秘鑰或運(yùn)算
Byte enNum = (byte) (aByte ^ key);
// 把加密后的數(shù)替換原集合中的數(shù)
byteList.set(i, enNum);
}
}
/**
* 生成加密/解密后的文件
*
* @param byteList
* @param outPath
* @throws IOException
*/
public static void writeText(List<Byte> byteList, String outPath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));
byte[] tempByte = new byte[byteList.size()];
for (int i = 0; i < byteList.size(); i++) {
tempByte[i] = byteList.get(i);
}
bos.write(tempByte);
bos.close();
}
}
input.txt文件內(nèi)容
將input的內(nèi)容加密后,寫入out.txt中
文件解密
文章來源:http://www.zghlxwxcb.cn/news/detail-533374.html
總結(jié)
這就是對(duì)文件內(nèi)容加密的簡(jiǎn)單實(shí)現(xiàn),這里的文件可以換成圖片或者其他類型的文件,都可以。另外,完全可以把inputPath和outPath設(shè)置成一樣,這樣就不會(huì)產(chǎn)生新文件了,運(yùn)行一次文件加密,再運(yùn)行一次,文件解密,非常方便。文章來源地址http://www.zghlxwxcb.cn/news/detail-533374.html
到了這里,關(guān)于用java給文件加密的簡(jiǎn)單實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!