2017-2018-2 20165211 实验五《网络编程与安全》实验报告
實(shí)驗(yàn)五 網(wǎng)絡(luò)編程與安全
課程:JAVA程序設(shè)計(jì)
班級(jí):1652班
姓名:丁奕
學(xué)號(hào):20165211
指導(dǎo)教師:婁嘉鵬
實(shí)驗(yàn)日期:2018.5.28
實(shí)驗(yàn)名稱:網(wǎng)絡(luò)編程與安全
具體實(shí)驗(yàn)步驟及問(wèn)題
(一)網(wǎng)絡(luò)編程與安全-1
實(shí)驗(yàn)要求
知識(shí)點(diǎn)
棧:棧 (Stack)是一種只允許在表尾插入和刪除的線性表,有先進(jìn)后出(FILO),后進(jìn)先出(LIFO)的特點(diǎn)。允許插入和刪除的一端稱為棧頂(top),另一端稱為棧底(bottom)。
表達(dá)式Exp = S1 + OP + S2有三種標(biāo)識(shí)方法,例子(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計(jì)算后綴表達(dá)式:
- +: 依次彈出w1與w2,將w2+w1壓棧。精度為結(jié)果值精度
- -: 依次彈出w1與w2,將w2-w1壓棧
- : 依次彈出w1與w2,將w2w1壓棧。精度為結(jié)果值精度與precision中較大值
- / : 依次彈出w1與w2,將w2/w1壓棧。精度為precision
實(shí)驗(yàn)代碼
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);}} }實(shí)驗(yàn)截圖
(二) 網(wǎng)絡(luò)編程與安全-2
實(shí)驗(yàn)要求
1人負(fù)責(zé)客戶端,一人負(fù)責(zé)服務(wù)器
知識(shí)點(diǎn)
在編寫客戶端和服務(wù)器端之前,回顧了一下對(duì)網(wǎng)絡(luò)方面的知識(shí)的學(xué)習(xí):
客戶端程序使用Socket類建立負(fù)責(zé)連接到服務(wù)器的套接字對(duì)象。
Socket的構(gòu)造方法是Socket(String host,int port),host是服務(wù)器的IP地址,port是一個(gè)端口號(hào)。建立套接字對(duì)象可能發(fā)生IOException異常。
try{Socket clientSocket=new Socket("http://192.168.0.78",2010); }catch{}當(dāng)前套接字對(duì)象clientSocket建立后,clientSocket可以使用方法getIntStream()獲得一個(gè)輸出流,這個(gè)輸入流的源和服務(wù)器端的一個(gè)輸出流的目的地剛好相同,因此客戶端用輸入流可以讀取服務(wù)器寫入到輸出流中的數(shù)據(jù);clientSocket使用方法getOutputStream()獲得一個(gè)輸出流,這個(gè)輸出流的目的地和服務(wù)器端的一個(gè)輸入流的源剛好相同,因此服務(wù)器可以用輸入流可以讀取客戶寫入到輸出流中的數(shù)據(jù)。
為了使客戶成功地連接到服務(wù)器,服務(wù)器必須建立一個(gè)ServerSocket對(duì)象。
ServerSocket的構(gòu)造方法是ServerSocket(int port),其中端口號(hào)port,必須與客戶呼叫的端口號(hào)一致。
實(shí)驗(yàn)代碼
服務(wù)器端代碼: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("接收數(shù)據(jù)成功!");String message=new String(b,0,n);System.out.println("來(lái)自客戶端的數(shù)據(jù)內(nèi)容為:" + 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("輸入中綴表達(dá)式: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("發(fā)送數(shù)據(jù)成功!");is = socket.getInputStream();byte[] b = new byte[1024];int n = is.read(b);System.out.println("接收數(shù)據(jù)成功!");System.out.println("來(lái)自服務(wù)器的數(shù)據(jù)內(nèi)容為:" + new String(b, 0, n));} catch (Exception e) {e.printStackTrace();} finally {try {is.close();os.close();socket.close();} catch (Exception e2) {}}} }實(shí)驗(yàn)截圖
(三)網(wǎng)絡(luò)編程與安全-3
實(shí)驗(yàn)要求
1人負(fù)責(zé)客戶端,一人負(fù)責(zé)服務(wù)器
知識(shí)點(diǎn)
(1) 獲取密鑰生成器
KeyGenerator kg=KeyGenerator.getInstance("DESede");
(2) 初始化密鑰生成器
kg.init(168);
(3) 生成密鑰
SecretKey k=kg.generateKey( );
(4) 通過(guò)對(duì)象序列化方式將密鑰保存在文件中
FileOutputStream f=new FileOutputStream("key1.dat");
ObjectOutputStream b=new ObjectOutputStream(f);
b.writeObject(k);
實(shí)驗(yàn)代碼
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("未連接到服務(wù)器");}try {DataInputStream input = new DataInputStream(s.getInputStream());System.out.print("請(qǐng)輸入: \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);//指定后綴表達(dá)式為明文字符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("客戶端:要發(fā)送的文件不存在");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("服務(wù)器連接中斷");}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("客戶端發(fā)送數(shù)據(jù)包,大小為" + size);os.write(buffer, 0, size);os.flush();}} catch (FileNotFoundException e) {System.out.println("客戶端讀取文件出錯(cuò)");} catch (IOException e) {System.out.println("客戶端輸出文件出錯(cuò)");}finally{try {if(fis != null)fis.close();} catch (IOException e) {System.out.println("客戶端文件關(guān)閉出錯(cuò)");}}try {PrintStream ps1 = new PrintStream(s.getOutputStream());ps1.println("111/#" + sendfile1.getName() + "/#" + fis1.available());ps1.flush();} catch (IOException e) {System.out.println("服務(wù)器連接中斷");}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("客戶端發(fā)送數(shù)據(jù)包,大小為" + size);os.write(buffer1, 0, size);os.flush();}} catch (FileNotFoundException e) {System.out.println("客戶端讀取文件出錯(cuò)");} catch (IOException e) {System.out.println("客戶端輸出文件出錯(cuò)");}finally{try {if(fis1 != null)fis1.close();} catch (IOException e) {System.out.println("客戶端文件關(guān)閉出錯(cuò)");}}try{DataInputStream input = new DataInputStream(s.getInputStream());String ret = input.readUTF();System.out.println("服務(wù)器端返回過(guò)來(lái)的是: " + ret);} catch (Exception e) {e.printStackTrace();}finally {if (s == null) {try {s.close();} catch (IOException e) {System.out.println("客戶端 finally 異常:" + e.getMessage());}}}} }實(shí)驗(yàn)截圖
(四)網(wǎng)絡(luò)編程與安全-4
實(shí)驗(yàn)要求
1人負(fù)責(zé)客戶端,一人負(fù)責(zé)服務(wù)器
知識(shí)點(diǎn)
使用密鑰協(xié)定來(lái)交換對(duì)稱密鑰。執(zhí)行密鑰協(xié)定的標(biāo)準(zhǔn)算法是DH算法(Diffie-Hellman算法)
DH算法是建立在DH公鑰和私鑰的基礎(chǔ)上的, A需要和B共享密鑰時(shí),A和B各自生成DH公鑰和私鑰,公鑰對(duì)外公布而私鑰各自秘密保存。本實(shí)例將介紹Java中如何創(chuàng)建并部署DH公鑰和私鑰,以便后面一小節(jié)利用它創(chuàng)建共享密鑰。
編程思路:
(1) 讀取自己的DH私鑰和對(duì)方的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) 創(chuàng)建密鑰協(xié)定對(duì)象
KeyAgreement ka=KeyAgreement.getInstance("DH");(3) 初始化密鑰協(xié)定對(duì)象
ka.init(prk);(4) 執(zhí)行密鑰協(xié)定
ka.doPhase(pbk,true);(5) 生成共享信息
byte[ ] sb=ka.generateSecret();實(shí)驗(yàn)代碼
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{//三個(gè)靜態(tài)變量的定義從 // C:\j2sdk-1_4_0-doc\docs\guide\security\jce\JCERefGuide.html // 拷貝而來(lái) // 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);} }實(shí)驗(yàn)截圖
網(wǎng)絡(luò)編程與安全-5
實(shí)驗(yàn)要求
1人負(fù)責(zé)客戶端,一人負(fù)責(zé)服務(wù)器
知識(shí)點(diǎn)
使用Java計(jì)算指定字符串的消息摘要。
java.security包中的MessageDigest類提供了計(jì)算消息摘要的方法,
首先生成對(duì)象,執(zhí)行其update()方法可以將原始數(shù)據(jù)傳遞給該對(duì)象,然后執(zhí)行其digest( )方法即可得到消息摘要。具體步驟如下:
(1) 生成MessageDigest對(duì)象
MessageDigest m=MessageDigest.getInstance("MD5");
(2) 傳入需要計(jì)算的字符串
m.update(x.getBytes("UTF8" ));
(3) 計(jì)算消息摘要
byte s[ ]=m.digest( );
(4) 處理計(jì)算結(jié)果
實(shí)驗(yàn)代碼
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);}實(shí)驗(yàn)截圖
轉(zhuǎn)載于:https://www.cnblogs.com/akashi/p/9129922.html
總結(jié)
以上是生活随笔為你收集整理的2017-2018-2 20165211 实验五《网络编程与安全》实验报告的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: linux iptables 详解
- 下一篇: 学习了Python那么长的世界,有没有玩