用base64加密解密文件

来源:互联网 发布:无锡美工培训学校 编辑:程序博客网 时间:2024/06/06 02:10

用jdk的base64工具加密一副图片,

思路是:先将图片加密,得到加密后的字符串,然后保存到本地磁盘的某个txt文件,然后读出这个文件,将其中的内容独到byte数组中,再解密。得到解密后的字节数组,通过流,写到本地磁盘上,得到一副图片。

加密方法:

static String filedc() throws Exception {InputStream is = null;File file = new File("E:/a.png");String fileString = "";try {is = new FileInputStream(file);  //得到源图片的输入流byte[] b = new byte[is.available()];//取得他的可用字节大小is.read(b); //将可用字节数组塞满BASE64Encoder be = new BASE64Encoder();// 构建加密对象fileString = be.encode(b);//将字节数组加密为字符串System.out.println(fileString);} catch (Exception e) {e.printStackTrace();} finally {is.close();}return fileString;//返回字符串}2.将字符串保存到本地磁盘上。比如E:/1.txt3,读取1.txt,并输出一副图片static void fromfile() throws Exception {BASE64Decoder bd = new BASE64Decoder();OutputStream os = null;InputStream is = null;File sfile = new File("E:1.txt");  //加密字符串所在的路径File file = new File("E:/b.png");//解密后的图片路径try {is = new FileInputStream(sfile);//将加密字符串所在的文件放到输入流中byte[] by = new byte[is.available()];//建立足够大的字节数组is.read(by); //独到字节数组中byte[] b = bd.decodeBuffer(new String(by));//将这个字节数组再解密到另一个字节数组中os = new FileOutputStream(file);//将解密后的图片放入输出流中os.write(b); //将解密后的字节数组写到输出流中} catch (Exception e) {e.printStackTrace();} finally {os.flush();os.close();is.close();}}


通过上述步骤,在e盘下可以找到解密后的图片。

jdk的base64据说不太安全,不过自己玩玩足够了,加密一些平时的图片,还可以。

原创粉丝点击