服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

技巧:用java语言实现对称加密实例详解

加密可提高终端和网络通讯的物理安全,有三种方法加密传输数据:

* 链接加密:在网络节点间加密,在节点间传输加密,传送到节点后解密,不同节点对间用不同密码.

* 节点加密:与链接加密类似,不同的只是当数据在节点间传送时,不用明码格式传送,而是用特殊 的加密硬件进行解密和重加密,这种专用硬件通常旋转在安全保险箱中.

* 首尾加密:对进入网络的数据加密,然后待数据从网络传送出后再进行解密.网络本身并不会知 道正在传送的数据是加密数据.这一方法的优点是,网络上的每个用户(通常是每个机器的一个 用户)可有不同的加密关键词,并且网络本身不需增添任何专门的加密设备.缺点是每个系统必 须有一个加密设备和相应的软件(管理加密关键词)或者每个系统必须自己完成加密工作(当数 据传输率是按兆位/秒的单位计算时,加密任务的计算量是很大的)

本文采用首尾加密,代码如下:

//从密钥文件中读密钥

   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);

      }

扫描关注微信公众号