站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题BouncyCastle JCE实践(四)

BouncyCastle JCE实践(四)

摘要: BouncyCastle JCE实践(四)

对称加密的实现 加密可提高终端和网络通讯的物理安全,有三种方法加密传输数据: * 链接加密:在网络节点间加密,在节点间传输加密,传送到节点后解密,不同节点对间用不同密码. * 节点加密:与链接加密类似,不同的只是当数据在节点间传送时,不用明码格式传送,而是用特殊 的加密硬件进行解密和重加密,这种专用硬件通常旋转在安全保险箱中. * 首尾加密:对进入网络的数据加密,然后待数据从网络传送出后再进行解密.网络本身并不会知 道正在传送的数据是加密数据.这一方法的优点是,网络上的每个用户(通常是每个机器的一个 用户)可有不同的加密关键词,并且网络本身不需增添任何专门的加密设备.缺点是每个系统必 须有一个加密设备和相应的软件(管理加密关键词)或者每个系统必须自己完成加密工作(当数 据传输率是按兆位/秒的单位计算时,加密任务的计算量是很大的)
本文采用首尾加密,代码如下:
//从密钥文件中读密钥
SecretKey key=null;
try {
//从密钥文件读取密钥
ObjectInputStream keyFile=new ObjectInputStream(
new FileInputStream("c:\\安全文件\\"+misClass.username+"\\对称\\对称密钥\\yhb.des"));
key=(SecretKey)keyFile.readObject();
keyFile.close(); }
catch(FileNotFoundException ey1) {
System.out.println("Error when read keyFile");
System.exit(0); }
catch(Exception ey2) {
System.out.println("error when read the keyFile");
System.exit(0); }
//用key产生Cipher
Cipher cipher=null;
try {
//加密要用Cipher来实现
cipher=Cipher.getInstance("DES");
//设置加密模式
cipher.init(Cipher.ENCRYPT_MODE,key);
}catch(Exception ey3) {
System.out.println("Error when create the cipher");
System.exit(0); }
//从对话框中取得要加密的文件
File file=new File(dirstring,string1);
String filename=file.getName();
//读入并加密文件
try {
//输入流
BufferedInputStream in=new BufferedInputStream(new FileInputStream(file));
//输出流
CipherOutputStream out=new CipherOutputStream(new BufferedOutputStream(
new FileOutputStream("c:\\安全文件\\文件\\"+filename+".yhb")),cipher);
int i;
do{
i=in.read();
if(i!=-1) out.write(i);
}while(i!=-1);
in.close();
out.close(); }
catch(Exception ey5) {
System.out.println("Error when encrypt the file");
System.exit(0); }
↑返回目录
前一篇: BouncyCastle JCE实践(五)
后一篇: BouncyCastle JCE实践(三)