首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

RSA加密Socket传输资料、签名(三)

2012-12-20 
RSA加密Socket传输文件、签名(三)接下来是客户端类CoderClient的编写。1.首先配置如下信息,包括服务器地址、

RSA加密Socket传输文件、签名(三)

接下来是客户端类CoderClient的编写。

1.首先配置如下信息,包括服务器地址、端口、密钥文件位置.

conf.properties

?

view plaincopy to clipboardprint?
  1. #configure?private?key?on?server??rsa_private=d:/rsa1_private.key??
  2. #public?key?from?client??rsa_public=d:/rsa_public.key??
  3. #server??server=127.0.0.1??
  4. #server?port??port=888??

?

?

?

2.编写发送文件的方法,其中byte[] buf=new byte[117]的原因是RSA加密算法支持的最大字节数为117,而加密后变成128位,所以服务器端解密的时候可以使用128bytes的buf读取文件。

?

view plaincopy to clipboardprint?
  1. public?boolean?send(String?filename){??????????try?{??
  2. ????????????File?f?=?new?File(filename);??????????????fis?=?new?FileInputStream(filename);??
  3. ????????????byte[]?buf?=?new?byte[117];??????????????int?available;??
  4. ????????????socket?=?new?Socket(server,port);??????????????os?=?socket.getOutputStream();??
  5. ????????????DataOutputStream?dos?=?new?DataOutputStream(os);??????????????dos.writeUTF(f.getName());?//写入文件名 ??
  6. ????????????dos.writeLong(f.length());?//写入文件大小 ??????????????while((available?=?fis.read(buf))?!=?-1){??
  7. ????????????????byte[]?availableBytes?=?null;??????????????????if(available?==?buf.length){??
  8. ????????????????????availableBytes?=?buf;??????????????????}else{??
  9. ????????????????????availableBytes?=?new?byte[available];??????????????????????for?(int?i?=?0;?i?<?available;?i++)?{??
  10. ????????????????????????availableBytes[i]?=?(byte)?buf[i];??????????????????????}??
  11. ????????????????}??????????????????byte[]?cipherText?=?coder.encrypt(availableBytes);??
  12. ????????????????byte[]?signature?=?sign.getSignature(cipherText);??????????????????os.write(signature);??
  13. ????????????????os.write(cipherText);??????????????????//count?+=?cipherText.length; ??
  14. ????????????????//System.out.println("send?"+count+"?bytes"); ??????????????}??
  15. ????????????socket.shutdownOutput();??????????????fis.close();??
  16. ????????????return?true;??????????}?catch?(FileNotFoundException?e)?{??
  17. ????????????log.error("文件"+filename+"?未找到");??????????}?catch?(UnknownHostException?e)?{??
  18. ????????????log.error("未知主机:"+server);??????????}?catch?(IOException?e)?{??
  19. ????????????log.error("文件读/写错误,可能是因为远程主机无响应");??????????}??
  20. ????????return?false;??????}??

?

?

?

?

3.为了测试多线程处理效果,可以将客户端继承于Thread,在重写的run方法中调用 send(String file)方法

?

view plaincopy to clipboardprint?
  1. @Override??????public?void?run()?{??
  2. ????????send(this.file);??????}??

?

?

?

4.main中的测试可以这样来模拟多个客户端同时向服务器传输文件

?

view plaincopy to clipboardprint?
  1. File?dir?=?new?File("E://files//demo//");??????????File[]?files?=?dir.listFiles();??
  2. ??????????????????for(int?i=0;?i<files.length;?i++){??
  3. ????????????Thread?th?=?new?Thread(new?CoderClient(files[i].getAbsolutePath()));??????????????th.start();??
  4. ????????}??

热点排行