RSA加密Socket传输资料、签名(三)
RSA加密Socket传输文件、签名(三)接下来是客户端类CoderClient的编写。1.首先配置如下信息,包括服务器地址、
RSA加密Socket传输文件、签名(三)
接下来是客户端类CoderClient的编写。
1.首先配置如下信息,包括服务器地址、端口、密钥文件位置.
conf.properties
?
view plaincopy to clipboardprint?
- #configure?private?key?on?server??rsa_private=d:/rsa1_private.key??
- #public?key?from?client??rsa_public=d:/rsa_public.key??
- #server??server=127.0.0.1??
- #server?port??port=888??
?
?
?
2.编写发送文件的方法,其中byte[] buf=new byte[117]的原因是RSA加密算法支持的最大字节数为117,而加密后变成128位,所以服务器端解密的时候可以使用128bytes的buf读取文件。
?
view plaincopy to clipboardprint?
- public?boolean?send(String?filename){??????????try?{??
- ????????????File?f?=?new?File(filename);??????????????fis?=?new?FileInputStream(filename);??
- ????????????byte[]?buf?=?new?byte[117];??????????????int?available;??
- ????????????socket?=?new?Socket(server,port);??????????????os?=?socket.getOutputStream();??
- ????????????DataOutputStream?dos?=?new?DataOutputStream(os);??????????????dos.writeUTF(f.getName());?//写入文件名 ??
- ????????????dos.writeLong(f.length());?//写入文件大小 ??????????????while((available?=?fis.read(buf))?!=?-1){??
- ????????????????byte[]?availableBytes?=?null;??????????????????if(available?==?buf.length){??
- ????????????????????availableBytes?=?buf;??????????????????}else{??
- ????????????????????availableBytes?=?new?byte[available];??????????????????????for?(int?i?=?0;?i?<?available;?i++)?{??
- ????????????????????????availableBytes[i]?=?(byte)?buf[i];??????????????????????}??
- ????????????????}??????????????????byte[]?cipherText?=?coder.encrypt(availableBytes);??
- ????????????????byte[]?signature?=?sign.getSignature(cipherText);??????????????????os.write(signature);??
- ????????????????os.write(cipherText);??????????????????//count?+=?cipherText.length; ??
- ????????????????//System.out.println("send?"+count+"?bytes"); ??????????????}??
- ????????????socket.shutdownOutput();??????????????fis.close();??
- ????????????return?true;??????????}?catch?(FileNotFoundException?e)?{??
- ????????????log.error("文件"+filename+"?未找到");??????????}?catch?(UnknownHostException?e)?{??
- ????????????log.error("未知主机:"+server);??????????}?catch?(IOException?e)?{??
- ????????????log.error("文件读/写错误,可能是因为远程主机无响应");??????????}??
- ????????return?false;??????}??
?
?
?
?
3.为了测试多线程处理效果,可以将客户端继承于Thread,在重写的run方法中调用 send(String file)方法
?
view plaincopy to clipboardprint?
- @Override??????public?void?run()?{??
- ????????send(this.file);??????}??
?
?
?
4.main中的测试可以这样来模拟多个客户端同时向服务器传输文件
?
view plaincopy to clipboardprint?
- File?dir?=?new?File("E://files//demo//");??????????File[]?files?=?dir.listFiles();??
- ??????????????????for(int?i=0;?i<files.length;?i++){??
- ????????????Thread?th?=?new?Thread(new?CoderClient(files[i].getAbsolutePath()));??????????????th.start();??
- ????????}??