java简单加密
本人是初学者,做了一个简单的文件加密,分享给大家,希望大家多多交流,告诉我一些好的方法
import java.io.*;public class Test {public static void main(String[] args) throws IOException {new Test().w("f:/Close.png");//new Test().r("f:/Close.yy","f:/Close.png");}/** * 将文件以二进制存入加密文件 * @param path 原文件完整路径 * @param newPath 新文件路径 * @throws IOException */public void w(String path,String newPath) throws IOException {FileInputStream fin = new FileInputStream(path);FileOutputStream fout = new FileOutputStream(newPath);int temp;try {while ((temp = fin.read()) != -1) {temp+=1;//自己写加密算法,改变temp(这里是关键,如果注释这一行,加密后的文件和原文件一样,也就不存在加密了)fout.write(temp);}} catch (IOException e) {e.printStackTrace();} finally {try {fin.close();fout.close();} catch (IOException e) {e.printStackTrace();}}}//这里是一个重载,可以不看public void w(String path) throws IOException {FileInputStream fin = new FileInputStream(path);String newPath = path.substring(0, path.lastIndexOf("."));newPath += ".yy";FileOutputStream fout = new FileOutputStream(newPath);int temp;try {while ((temp = fin.read()) != -1) {temp+=1;//自己写加密算法,同上fout.write(temp);}} catch (IOException e) {e.printStackTrace();} finally {try {fin.close();fout.close();} catch (IOException e) {e.printStackTrace();}}}/** * 将加密文件还原 * @param path 原文件完整路径 * @param newPath 新文件路径 * @throws IOException */public void r(String path,String newPath) throws FileNotFoundException{FileInputStream fin = new FileInputStream(path);FileOutputStream fout = new FileOutputStream(newPath);int temp;try {while ((temp = fin.read()) != -1) { temp-=1;//解密,和加密对应,加密是+1,这里就-1。fout.write(temp);}} catch (IOException ex1) {ex1.printStackTrace();} finally {try {fin.close();fout.close();} catch (IOException ex2) {ex2.printStackTrace();}}}}