20145308刘昊阳 《Java程序设计》实验五 Java网络编程及安全 实验报告
实验名称
Java网络编程及安全
实验内容
1.掌握Socket程序的编写;
2.掌握密码技术的使用;
3.设计安全传输系统。
统计的PSP(Personal Software Process)时间
步骤 | 耗时(min) | 百分比 |
---|---|---|
需求分析 | 20~30 | 17% |
设计 | 20~30 | 17% |
代码实现 | 10~20 | 11% |
测试 | 50~60 | 33% |
分析总结 | 30~40 | 22% |
实验步骤
- 我是做的服务器端,我的结伴对象是20145325张梓靖,地址:http://www.cnblogs.com/zzjzzjzzj/p/5471240.html
- 1.先利用示例代码运行,监听客户端
import java.io.*;
import java.net.*;
/*** 复用连接的echo服务器* 功能:将客户端发送的内容反馈给客户端*/
public class MulSocketServer {public static void main(String[] args) {ServerSocket serverSocket = null;Socket socket = null;OutputStream os = null;InputStream is = null;//监听端口号int port = 10000;try {//建立连接serverSocket = new ServerSocket(port);System.out.println("服务器已启动:");//获得连接socket = serverSocket.accept();//初始化流is = socket.getInputStream();os = socket.getOutputStream();byte[] b = new byte[1024];for(int i = 0;i < 2;i++){int n = is.read(b);//输出System.out.println("客户端发送内容为:" + new String(b,0,n));//向客户端发送反馈内容os.write(b, 0, n);}} catch (Exception e) {e.printStackTrace();}finally{try{//关闭流和连接os.close();is.close();socket.close();serverSocket.close();}catch(Exception e){}}}
}
接收到对方传送的字符串
2.生成公钥、私钥
KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");kpg.initialize(1024);KeyPair kp=kpg.genKeyPair();PublicKey pbkey=kp.getPublic();PrivateKey prkey=kp.getPrivate();FileOutputStream f1=new FileOutputStream("Skey_RSA_pub.dat");ObjectOutputStream b1=new ObjectOutputStream(f1);b1.writeObject(pbkey);FileOutputStream f2=new FileOutputStream("Skey_RSA_priv.dat");ObjectOutputStream b2=new ObjectOutputStream(f2);b2.writeObject(prkey);
- 3.利用解密算法对收到的密文进行解密
BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream("Enc_RSA.dat")));String ctext=in.readLine();BigInteger c=new BigInteger(ctext);FileInputStream f=new FileInputStream("Skey_RSA_priv.dat");ObjectInputStream b=new ObjectInputStream(f);RSAPrivateKey prk=(RSAPrivateKey)b.readObject( );BigInteger d=prk.getPrivateExponent();BigInteger n=prk.getModulus();System.out.println("d= "+d);System.out.println("n= "+n);BigInteger m=c.modPow(d,n);System.out.println("m= "+m);byte[] mt=m.toByteArray();System.out.println("PlainText is ");for(int i=0;i<mt.length;i++){System.out.print((char) mt[i]);
FileInputStream f=new FileInputStream("SEnc.dat");int num=f.available();byte[ ] ctext=new byte[num];f.read(ctext);FileInputStream f2=new FileInputStream("keykb1.dat");int num2=f2.available();byte[ ] keykb=new byte[num2];f2.read(keykb);SecretKeySpec k=new SecretKeySpec(keykb,"DESede");Cipher cp=Cipher.getInstance("DESede");cp.init(Cipher.DECRYPT_MODE, k);byte []ptext=cp.doFinal(ctext);String p=new String(ptext,"UTF8");System.out.println(p);