Java安全(四)-输入流的解密

本文介绍了一种基于Java的输入流解密方法,通过使用CipherInputStream实现文件的解密过程。文章详细展示了如何生成和使用密钥、初始化密码器、创建CipherInputStream对象并最终将解密内容写入文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


本实例演示针对输入流的解密,将JAVA安全笔记(三)-输入流加密 的加密文件进行解密,并把解密后的结果输入指定的另外一个文件

输入流的解密技术要点如下

1.密钥生成
2.初始化密码器
3.获取解密的内容
4.创建CipherInputStream对象
5.读取输入流
6.存入相应文件中


源代码

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

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;


public class D_InStream {
  public static void main(String[] args) throws Exception {
	//生成密钥
	FileInputStream f=new FileInputStream("C:\\Users\\Administrator\\Desktop\\key1.dat");
	ObjectInputStream ob=new ObjectInputStream(f);
	Key k=(Key)ob.readObject();
	Cipher cp=Cipher.getInstance("DESede"); //创建密码器
	cp.init(Cipher.DECRYPT_MODE, k);//初始化密码器,解密模式DECRYPT_MODE
	FileInputStream in=new FileInputStream("C:\\Users\\Administrator\\Desktop\\E_InStream.dat");
	CipherInputStream cin=new CipherInputStream(in, cp);//创建CiperInputStream对象
	int b=0;
	int i=1;
	FileOutputStream out =new  FileOutputStream("C:\\Users\\Administrator\\Desktop\\D_InStream.txt");//将密文保存到指定的文件中
	System.out.println("对文件输入流解密的原文如下");
	while((b=cin.read())!=-1){ //读输入流
		System.out.print((byte) b+" ");
		out.write((byte)b); // 书中代码中漏掉的,要往文件中写
		i++;  
		if(i%30 == 0)
			System.out.println();
	}
}
}


运行结果



源程序解读
(1) FileInputStream f=new FileInputStream("C:\\Users\\Administrator\\Desktop\\key1.dat");
该语句从文件所用的中读取加密时所用的密钥,这样保证了本实例的密钥和加密时的密钥相同,以便于对比解密后的结果

key1.dat的生成由 Java安全笔记(二)创建对称密钥

加密程序 JAVA安全笔记(三)-输入流加密
(2) FileInputStream in=new FileInputStream("C:\\Users\\Administrator\\Desktop\\E_InStream.dat");
该语句的作用是获取要解密的文件,本程序是以 加密程序生成的文件为例,文件名为E_InStream.dat
(3) CipherInputStream cin=new CipherInputStream(in, cp);
该语句的作用是创建CiperInputStream对象,根据前面所创建好的密码器和输入流为参数构造CipherInputStream对象
(4) 同java.io包中的基本的输入流一样使用read()方法从CipherInputStream流中读取数据。
则在读取过程中会自动根据密码器中的设置进行解密。











评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值