Java安全学习笔记(十)-输出流的加密和解密

本实例演示了针对输出流的加密和解密。
加密-将指定文件中的内容进行加密,并把加密的结果输入到指定的另外一个文件。
输出流的加密和解密技术要点如下:
1.密钥生成
2.初始化密码器
3.创建加密的输出流
4创建CipherOutputStream对象
5.写输出流
package core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
/**
 * 对输出流进行加密和解密
 * */
public class ED_OutStream {
	public static void main(String[] args) throws Exception {
		//获取密钥
		FileInputStream fis=new FileInputStream("key1.dat");
		ObjectInputStream ois=new ObjectInputStream(fis);
		Key k=(Key) ois.readObject(); //生成密钥
		//创建并初始化密码器
		Cipher cp=Cipher.getInstance("DESede");
		cp.init(Cipher.ENCRYPT_MODE, k);
		//获取需要加密的文件
		FileInputStream in = new FileInputStream("file.doc");// 创建要加密的输入流
		FileOutputStream out = new FileOutputStream("OutStream.dat");// 将密文保存到指定的文件中
		CipherOutputStream cout = new CipherOutputStream(out, cp);// 再由密码器输入流把输入流和密码器包装
		int b = 0;
		int i = 1;
		System.out.println("对文件输出流加密的密文如下:");
		while ((b = in.read()) != -1) {// 读取输入流
			cout.write((byte) b);// 把加密的输入流存入文件E_InStream.dat中
			System.out.print((byte) b + " ");
			i++;
			if (i % 30 == 0)
				System.out.println();

		}
		System.out.println();
		//System.out.println("=========解密===========");
		/* 解密 */
		// 创建并初始化密码器
		Cipher cp2 = Cipher.getInstance("DESede");// 创建由DES算法的密码器
		cp2.init(Cipher.DECRYPT_MODE, k);// 初始化密码器,第一个参数是选择密码器模式-加密模式,第二个参数是密钥
		FileInputStream fin = new FileInputStream("OutStream.dat");// 获取要解密的文件
		
		FileOutputStream out2=new FileOutputStream("file2.doc");//指定读出密文的文件
		CipherOutputStream cipherout = new CipherOutputStream(out2, cp2);
		int c = 0;
		//System.out.println("对文件输出流解密的密文如下:");
		while ((c = fin.read()) != -1) {// 写出流
			cipherout.write(c);//把解密后的明文写入file2.doc中
		}
		//关闭流
		ois.close();
		in.close();
		cout.close();
		out.close();
		fin.close();
		cipherout.close();
		
	}
}



源程序解读
(1)生成密钥、创建并初始化密码器、创建要加密的输出流这三个步骤与输入流的加解密是一样的,
(2)FileInputStream in = new FileInputStream("file.doc");语句的主要作用是获取要加密或解密的内容。要加密的内容可以是各种形式,只要可以转换为整形或字节数组形式即可。
(3)使用write()方法向CipherOutputStream流中写数据(数据为需要加密的明文,本实例使用read()方法从文件中读取明文),则在写之前CipherOutputStream流会自动按照其参数中的密码器设置先进行加密或者解密操作,然后再写入其参数的输出流中。
(4)加密的结果可以输出到各种输出流中,本实例将加密结果保存为文件,因此创建文件输出流,将其和前面创建好的密码器一起作为参数传递给CipherOutputStream对象。解密的结果输出到文件file2.doc中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值