2017-2018-2 20165211 实验五《网络编程与安全》实验报告
实验五 网络编程与安全
课程:JAVA程序设计
班级:1652班
姓名:丁奕
学号:20165211
指导教师:娄嘉鹏
实验日期:2018.5.28
实验名称:网络编程与安全
具体实验步骤及问题
(一)网络编程与安全-1
实验要求
知识点
栈:栈 (Stack)是一种只允许在表尾插入和删除的线性表,有先进后出(FILO),后进先出(LIFO)的特点。允许插入和删除的一端称为栈顶(top),另一端称为栈底(bottom)。
表达式Exp = S1 + OP + S2有三种标识方法,例子(a * b + (c - d / e) * f):
- OP + S1 + S2 为前缀表示法:+ * a b * - c / d e f
- S1 + OP + S2 为中缀表示法: a * b + c - d / e * f
- S1 + S2 + OP 为后缀表示法:a b * c d e / - f * +
dc计算后缀表达式:
- +: 依次弹出w1与w2,将w2+w1压栈。精度为结果值精度
- -: 依次弹出w1与w2,将w2-w1压栈
- : 依次弹出w1与w2,将w2w1压栈。精度为结果值精度与precision中较大值
- / : 依次弹出w1与w2,将w2/w1压栈。精度为precision
实验代码
MyDC:
import java.util.StringTokenizer; import java.util.Stack;public class MyDC {private final char ADD = '+';private final char SUBTRACT = '-';private final char MULTIPLY = '*';private final char DIVIDE = '/';private Stack<Integer> stack;public MyDC() {stack = new Stack<Integer>();}public int evaluate(String expr) {int op1, op2, result = 0;String token;StringTokenizer tokenizer = new StringTokenizer(expr);while (tokenizer.hasMoreTokens()) {token = tokenizer.nextToken();if (isOperator(token)) {op2 = (stack.pop()).intValue();op1 = (stack.pop()).intValue();result = evalSingleOp(token.charAt(0), op1, op2);stack.push(new Integer(result));} elsestack.push(new Integer(Integer.parseInt(token)));}return result;}private boolean isOperator(String token) {return (token.equals("+") || token.equals("-") ||token.equals("*") || token.equals("/"));}private int evalSingleOp(char operation, int op1, int op2) {int result = 0;switch (operation) {case ADD:result = op1 + op2;break;case SUBTRACT:result = op1 - op2;break;case MULTIPLY:result = op1 * op2;break;case DIVIDE:result = op1 / op2;}return result;} }MyDCTest:
import java.util.Scanner; public class MyDCTest {public static void main (String[] args) {String expression, again;int result;try {Scanner in = new Scanner(System.in);do {MyDC evaluator = new MyDC();System.out.println ("Enter a valid postfix expression: ");expression = in.nextLine();result = evaluator.evaluate (expression);System.out.println();System.out.println ("That expression equals " + result);System.out.print ("Evaluate another expression [Y/N]? ");again = in.nextLine();System.out.println();}while (again.equalsIgnoreCase("y"));}catch (Exception IOException) { System.out.println("Input exception reported"); } } }MyBC:
import java.io.IOException; import java.util.Scanner; public class MyBC {private Stack theStack;private String input;private String output = "";public MyBC(String in) {input = in;int stackSize = input.length();theStack = new Stack(stackSize);}public String doTrans() {for (int j = 0; j < input.length(); j++) {char ch = input.charAt(j);switch (ch) {case '+':case '-':gotOper(ch, 1);break;case '*':case '/':gotOper(ch, 2);break;case '(':theStack.push(ch);break;case ')':gotParen(ch);break;default:output = output + ch;break;}}while (!theStack.isEmpty()) {output = output + theStack.pop();}System.out.println(output);return output;}public void gotOper(char opThis, int prec1) {while (!theStack.isEmpty()) {char opTop = theStack.pop();if (opTop == '(') {theStack.push(opTop);break;}else {int prec2;if (opTop == '+' || opTop == '-')prec2 = 1;elseprec2 = 2;if (prec2 < prec1) {theStack.push(opTop);break;}elseoutput = output + opTop;}}theStack.push(opThis);}public void gotParen(char ch){while (!theStack.isEmpty()) {char chx = theStack.pop();if (chx == '(')break;elseoutput = output + chx;}}public static void main(String[] args) throws IOException {Scanner in = new Scanner(System.in);String input = in.nextLine();System.out.println(input);String output;MyBC theTrans = new MyBC(input);output = theTrans.doTrans();}class Stack {private int maxSize;private char[] stackArray;private int top;public Stack(int max) {maxSize = max;stackArray = new char[maxSize];top = -1;}public void push(char j) {stackArray[++top] = j;}public char pop() {return stackArray[top--];}public char peek() {return stackArray[top];}public boolean isEmpty() {return (top == -1);}} }实验截图
(二) 网络编程与安全-2
实验要求
1人负责客户端,一人负责服务器
知识点
在编写客户端和服务器端之前,回顾了一下对网络方面的知识的学习:
客户端程序使用Socket类建立负责连接到服务器的套接字对象。
Socket的构造方法是Socket(String host,int port),host是服务器的IP地址,port是一个端口号。建立套接字对象可能发生IOException异常。
try{Socket clientSocket=new Socket("http://192.168.0.78",2010); }catch{}当前套接字对象clientSocket建立后,clientSocket可以使用方法getIntStream()获得一个输出流,这个输入流的源和服务器端的一个输出流的目的地刚好相同,因此客户端用输入流可以读取服务器写入到输出流中的数据;clientSocket使用方法getOutputStream()获得一个输出流,这个输出流的目的地和服务器端的一个输入流的源刚好相同,因此服务器可以用输入流可以读取客户写入到输出流中的数据。
为了使客户成功地连接到服务器,服务器必须建立一个ServerSocket对象。
ServerSocket的构造方法是ServerSocket(int port),其中端口号port,必须与客户呼叫的端口号一致。
实验代码
服务器端代码:Server
import java.io.*; import java.net.*; import static java.lang.Integer.*;public class Server {public static void main(String[] args) {ServerSocket serverSocket = null;Socket socket = null;OutputStream os = null;InputStream is = null;int port = 8087;try {serverSocket = new ServerSocket(port);System.out.println("建立连接成功!");socket = serverSocket.accept();System.out.println("获得连接成功!");is = socket.getInputStream();byte[] b = new byte[1024];int n = is.read(b);System.out.println("接收数据成功!");String message=new String(b,0,n);System.out.println("来自客户端的数据内容为:" + message);String output;MyBC theTrans = new MyBC(message);output = theTrans.doTrans();os = socket.getOutputStream();os.write(output.getBytes());} catch (Exception e) {e.printStackTrace();}finally{try{os.close();is.close();socket.close();serverSocket.close();}catch(Exception e){}}} }客户端代码:Client
import java.io.*; import java.net.*; public class Client {public static void main(String[] args) {Socket socket = null;InputStream is = null;OutputStream os = null;String serverIP = "172.16.252.50";int port = 8087;System.out.println("输入中缀表达式:20-16/4+52-11*2");String output;MyBC theTrans = new MyBC("20-16/4+52-11*2");output = theTrans.doTrans();try {socket = new Socket(serverIP, port);System.out.println("建立连接成功!");os = socket.getOutputStream();os.write(output.getBytes());System.out.println("发送数据成功!");is = socket.getInputStream();byte[] b = new byte[1024];int n = is.read(b);System.out.println("接收数据成功!");System.out.println("来自服务器的数据内容为:" + new String(b, 0, n));} catch (Exception e) {e.printStackTrace();} finally {try {is.close();os.close();socket.close();} catch (Exception e2) {}}} }实验截图
(三)网络编程与安全-3
实验要求
1人负责客户端,一人负责服务器
知识点
(1) 获取密钥生成器
KeyGenerator kg=KeyGenerator.getInstance("DESede");
(2) 初始化密钥生成器
kg.init(168);
(3) 生成密钥
SecretKey k=kg.generateKey( );
(4) 通过对象序列化方式将密钥保存在文件中
FileOutputStream f=new FileOutputStream("key1.dat");
ObjectOutputStream b=new ObjectOutputStream(f);
b.writeObject(k);
实验代码
ClientSend
import java.io.*;import java.net.Socket;public class ClientSend {public static void main(String[] args) {Socket s = null;try {s = new Socket("192.168.56.1", 12345);}catch (IOException e) {System.out.println("未连接到服务器");}try {DataInputStream input = new DataInputStream(s.getInputStream());System.out.print("请输入: \t");String str = new BufferedReader(new InputStreamReader(System.in)).readLine();MyBC turner = new MyBC();String str1 = turner.turn(str);int length = 0, i = 0;while (str1.charAt(i) != '\0') {length++;i++;}String str2 = str1.substring(1, length - 1);SEnc senc = new SEnc(str2);//指定后缀表达式为明文字符senc.encrypt();//加密}catch(Exception e) {System.out.println("客户端异常:" + e.getMessage());}File sendfile = new File("SEnc.dat");File sendfile1 = new File("Keykb1.dat");FileInputStream fis = null;FileInputStream fis1 = null;byte[] buffer = new byte[4096 * 5];byte[] buffer1 = new byte[4096 * 5];OutputStream os;if(!sendfile.exists() || !sendfile1.exists()){System.out.println("客户端:要发送的文件不存在");return;}try {fis = new FileInputStream(sendfile);fis1 = new FileInputStream(sendfile1);} catch (FileNotFoundException e1) {e1.printStackTrace();}try {PrintStream ps = new PrintStream(s.getOutputStream());ps.println("111/#" + sendfile.getName() + "/#" + fis.available());ps.flush();} catch (IOException e) {System.out.println("服务器连接中断");}try {Thread.sleep(2000);} catch (InterruptedException e1) {e1.printStackTrace();}try {os = s.getOutputStream();int size = 0;while((size = fis.read(buffer)) != -1){System.out.println("客户端发送数据包,大小为" + size);os.write(buffer, 0, size);os.flush();}} catch (FileNotFoundException e) {System.out.println("客户端读取文件出错");} catch (IOException e) {System.out.println("客户端输出文件出错");}finally{try {if(fis != null)fis.close();} catch (IOException e) {System.out.println("客户端文件关闭出错");}}try {PrintStream ps1 = new PrintStream(s.getOutputStream());ps1.println("111/#" + sendfile1.getName() + "/#" + fis1.available());ps1.flush();} catch (IOException e) {System.out.println("服务器连接中断");}try {Thread.sleep(2000);} catch (InterruptedException e1) {e1.printStackTrace();}try {os = s.getOutputStream();int size = 0;while((size = fis1.read(buffer1)) != -1){System.out.println("客户端发送数据包,大小为" + size);os.write(buffer1, 0, size);os.flush();}} catch (FileNotFoundException e) {System.out.println("客户端读取文件出错");} catch (IOException e) {System.out.println("客户端输出文件出错");}finally{try {if(fis1 != null)fis1.close();} catch (IOException e) {System.out.println("客户端文件关闭出错");}}try{DataInputStream input = new DataInputStream(s.getInputStream());String ret = input.readUTF();System.out.println("服务器端返回过来的是: " + ret);} catch (Exception e) {e.printStackTrace();}finally {if (s == null) {try {s.close();} catch (IOException e) {System.out.println("客户端 finally 异常:" + e.getMessage());}}}} }实验截图
(四)网络编程与安全-4
实验要求
1人负责客户端,一人负责服务器
知识点
使用密钥协定来交换对称密钥。执行密钥协定的标准算法是DH算法(Diffie-Hellman算法)
DH算法是建立在DH公钥和私钥的基础上的, A需要和B共享密钥时,A和B各自生成DH公钥和私钥,公钥对外公布而私钥各自秘密保存。本实例将介绍Java中如何创建并部署DH公钥和私钥,以便后面一小节利用它创建共享密钥。
编程思路:
(1) 读取自己的DH私钥和对方的DH公钥
FileInputStream f1=new FileInputStream(args[0]); ObjectInputStream b1=new ObjectInputStream(f1); PublicKey pbk=(PublicKey)b1.readObject( ); FileInputStream f2=new FileInputStream(args[1]); ObjectInputStream b2=new ObjectInputStream(f2); PrivateKey prk=(PrivateKey)b2.readObject( );(2) 创建密钥协定对象
KeyAgreement ka=KeyAgreement.getInstance("DH");(3) 初始化密钥协定对象
ka.init(prk);(4) 执行密钥协定
ka.doPhase(pbk,true);(5) 生成共享信息
byte[ ] sb=ka.generateSecret();实验代码
Key_DH:
import java.io.*; import java.math.*; import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*;public class Key_DH{//三个静态变量的定义从 // C:\j2sdk-1_4_0-doc\docs\guide\security\jce\JCERefGuide.html // 拷贝而来 // The 1024 bit Diffie-Hellman modulus values used by SKIPprivate static final byte skip1024ModulusBytes[] = {(byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,(byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,(byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,(byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,(byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,(byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,(byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,(byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,(byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,(byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,(byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,(byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,(byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,(byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,(byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,(byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,(byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,(byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,(byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,(byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,(byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,(byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,(byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,(byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,(byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,(byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,(byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,(byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,(byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,(byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,(byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,(byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7};// The SKIP 1024 bit modulusprivate static final BigInteger skip1024Modulus= new BigInteger(1, skip1024ModulusBytes);// The base used with the SKIP 1024 bit modulusprivate static final BigInteger skip1024Base = BigInteger.valueOf(2); public static void main(String args[ ]) throws Exception{DHParameterSpec DHP= new DHParameterSpec(skip1024Modulus,skip1024Base);KeyPairGenerator kpg= KeyPairGenerator.getInstance("DH");kpg.initialize(DHP);KeyPair kp=kpg.genKeyPair();PublicKey pbk=kp.getPublic();PrivateKey prk=kp.getPrivate();// 保存公钥FileOutputStream f1=new FileOutputStream(args[0]);ObjectOutputStream b1=new ObjectOutputStream(f1);b1.writeObject(pbk);// 保存私钥FileOutputStream f2=new FileOutputStream(args[1]);ObjectOutputStream b2=new ObjectOutputStream(f2);b2.writeObject(prk);} }实验截图
网络编程与安全-5
实验要求
1人负责客户端,一人负责服务器
知识点
使用Java计算指定字符串的消息摘要。
java.security包中的MessageDigest类提供了计算消息摘要的方法,
首先生成对象,执行其update()方法可以将原始数据传递给该对象,然后执行其digest( )方法即可得到消息摘要。具体步骤如下:
(1) 生成MessageDigest对象
MessageDigest m=MessageDigest.getInstance("MD5");
(2) 传入需要计算的字符串
m.update(x.getBytes("UTF8" ));
(3) 计算消息摘要
byte s[ ]=m.digest( );
(4) 处理计算结果
实验代码
Server修改:
String x= exp;MessageDigest m=MessageDigest.getInstance("MD5");m.update(x.getBytes("UTF8"));byte s[ ]=m.digest( );String res="";for (int j=0; j<s.length; j++){res +=Integer.toHexString((0x000000ff & s[j]) |0xffffff00).substring(6);}System.out.printf("md5Check:" + md5.equals(res));Client修改:
String x= str2;MessageDigest m=MessageDigest.getInstance("MD5");m.update(x.getBytes("UTF8"));byte s[ ]=m.digest( );String result="";for (int j=0; j<s.length; j++){result+=Integer.toHexString((0x000000ff & s[j]) |0xffffff00).substring(6);}实验截图
转载于:https://www.cnblogs.com/akashi/p/9129922.html
总结
以上是生活随笔为你收集整理的2017-2018-2 20165211 实验五《网络编程与安全》实验报告的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: linux iptables 详解
- 下一篇: Flex入坑指南