标签:.com ade 否则 int() 实验代码 strong post 技术分享 remove
课程:Java程序设计 班级:1653班 姓名:孙晓暄 学号:20165318
指导教师:娄嘉鹏 实验日期:2018年5月28日
实验时间:13:45 - 3:25 实验序号:实验五
实验名称:网络编程与安全
实验要求
实验原理
将运算符写在两个操作数中间的表达式,称为“中缀表达式”,如1+2*(3-4)+5。在中缀表达式中,运算符具有不同的优先级,圆括号用于改变运算符的运算次序,所以求值过程不能直接按照从左到右的顺序进行。
将运算符写在两个操作数之后的表达式称为“后缀表达式”,如上面的中缀表达式可转换为后缀表达式1 2 3 4 - * + 5 +
。后缀表达式中没有括号,而且运算符没有优先级。后缀表达式的求值过程能够严格地从左到右按顺序进行,符合运算器的求值规律。
表达式求值算法分两步进行:①中缀转后缀;②求后缀表达式的值。
由中缀式求得后缀式可以使用栈,伪代码如下:
后缀表达式求值伪代码如下:
实验代码
MyBC.java
import java.util.*;
public class MyBC {
private Stack<String> stack;
private List<String> list;
private String message, Message = "";
public MyBC() {
stack = new Stack<String>();//用来暂时存放运算符的栈
list = new ArrayList<String>();//用来暂时存放操作数及运算符的列表
}
public void conversion(String expr) { //中缀转后缀
String token;
StringTokenizer tokenizer = new StringTokenizer(expr);
while (tokenizer.hasMoreTokens()) {
//当tokenizer有下一个值时,进行循环,并把值赋给token
token = tokenizer.nextToken();
if (token.equals("(")) {
//如果是左括号,入栈
stack.push(token);
} else if (token.equals("+") || token.equals("-")) {
//如果是“+”或“-”,继续判断栈是否为空
if (!stack.empty()) {
//如果栈非空,判断栈顶元素是什么
if (stack.peek().equals("(")) {
//如果栈顶为“(”,运算符入栈
stack.push(token);
} else {
//否则先把栈顶元素移除,加到列表中,再将运算符入栈
list.add(stack.pop());
stack.push(token);
}
} else {
//若栈为空,运算符入栈
stack.push(token);
}
} else if (token.equals("*") || token.equals("÷")) {
//如果是“*”或“÷”,继续判断栈是否为空
if (!stack.empty()) {
//如果栈非空,判断栈顶元素是什么
if (stack.peek().equals("*") || stack.peek().equals("÷")) {
//如果栈顶为“*”或“÷”,先把栈顶元素移除,加到列表中,再将运算符入栈
list.add(stack.pop());
stack.push(token);
} else {
//如果栈顶为其他,运算符直接入栈
stack.push(token);
}
} else {
//如果栈为空,运算符直接入栈
stack.push(token);
}
} else if (token.equals(")")) {
//如果遇到“)”,开始循环
while (true) {
//先把栈顶元素移除并赋给A
String A = stack.pop();
if (!A.equals("(")) {
//如果A不为“(”,则加到列表
list.add(A);
} else {
//如果A为“(”,退出循环
break;
}
}
} else {
//如果为操作数,进入列表
list.add(token);
}
}
while (!stack.empty()) {
//将栈中元素取出,加到列表中,直到栈为空
list.add(stack.pop());
}
ListIterator<String> li = list.listIterator();//返回此列表元素的列表迭代器(按适当顺序)。
while (li.hasNext()) {
//将迭代器中的元素依次取出,并加上空格作为分隔符
Message += li.next() + " ";
li.remove();
}
message = Message;
}
public String getMessage() {
return message;
}
}
MyDC.java
import java.util.*;
public class MyDC {
private final char ADD = ‘+‘;
private final char SUBTRACT = ‘-‘;
private final char MUTIPLY = ‘*‘;
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));
}
else {
stack.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 MUTIPLY:
result = op1*op2;
break;
case DIVIDE:
result = op1/op2;
}
return result;
}
}
测试代码
Calculator.java
import java.util.*;
public class Calculator {
public static void main(String[] args) {
String expression;
int result;
MyBC nts = new MyBC();
MyDC value = new MyDC();
System.out.println("Please input a nifix expression");
Scanner in = new Scanner(System.in);
expression = in.nextLine();
nts.conversion(expression);
System.out.println("The postfix expression is :"+nts.getMessage());
result = value.evaluate(nts.getMessage());
System.out.println("The result is :"+result);
}
}
实验截图
实验要求
实验原理
『java.net.Socket』:
public Socket(java.lang.String host, int port)
。其中,host是远程机器名或IP地址,port是远程应用程序的端口号。『java.net.ServerSocket』:
实验代码
调用任务一中的MyBC.java和MyDC.java,将中缀表达式转后缀表达式,并对后缀表达式求值。
查看自己电脑的IP地址:
Address.java
import java.net.*;
public class Address {
public static void main(String[] args) throws UnknownHostException {
InetAddress net = InetAddress.getLocalHost();
System.out.println(net.toString());
}
}
客户端
import java.io.*;
import java.net.*;
public class Client2 {
public static void main(String args[]) {
System.out.println("客户端启动...");
//while (true) {
Socket mysocket;
DataInputStream in = null;
DataOutputStream out = null;
try {
mysocket = new Socket("192.168.188.1", 2010);
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
System.out.println("请输入:");
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
MyBC turner = new MyBC();
turner.conversion(str);
String str1 = turner.getMessage();
out.writeUTF(str1);
String s = in.readUTF(); //in读取信息,堵塞状态
System.out.println("客户收到服务器的回答:" + s);
Thread.sleep(500);
} catch (Exception e) {
System.out.println("服务器已断开" + e);
}
//}
}
}
服务器端
import java.io.*;
import java.net.*;
public class Server2 {
public static void main(String[] args) throws IOException {
int answer;
//while (true) {
ServerSocket serverForClient = null;
Socket socketOnServer = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
serverForClient = new ServerSocket(2010);
} catch (IOException e1) {
System.out.println(e1);
}
try {
System.out.println("等待客户呼叫");
socketOnServer = serverForClient.accept(); //堵塞状态,除非有客户呼叫
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
String s = in.readUTF(); // in读取信息,堵塞状态
System.out.println("服务器收到客户的提问:" + s);
MyDC myDC = new MyDC();
answer = myDC.evaluate(s);
out.writeUTF(answer + "");
Thread.sleep(500);
} catch (Exception e) {
System.out.println("客户已断开" + e);
}
//}
}
}
实验截图
实验要求
实验原理
实验代码
DES生成密钥并加解密的程序参考Java 密码学算法在此就不一一列出
客户端
import javax.crypto.Cipher;
import java.io.*;
import java.net.Socket;
import java.security.Key;
import java.util.Scanner;
public class Client3 {
public static void main(String args[]) {
Socket mysocket;
MyBC mybc = new MyBC();
DataInputStream in = null;
DataOutputStream out = null;
Scanner scanner = new Scanner(System.in);
String str;
try {
mysocket = new Socket("192.168.188.1", 5318);
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
System.out.println("客户端启动...");
FileInputStream f = new FileInputStream("key1.dat");
ObjectInputStream b = new ObjectInputStream(f);
Key key = (Key) b.readObject();
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, key);
System.out.println("请输入中缀表达式:");
str = scanner.nextLine();
mybc.conversion(str);
String str1 = mybc.getMessage();
byte ptext[] = str1.getBytes("UTF-8");
byte ctext[] = cp.doFinal(ptext);
System.out.println("被加密的后缀表达式:");
for (int i = 0; i < ctext.length; i++) {
System.out.print(ctext[i] + ",");
}
System.out.println("");
out.writeUTF(ctext.length + "");
for (int i = 0; i < ctext.length; i++) {
out.writeUTF(ctext[i] + "");
//System.out.print();
}
String s = in.readUTF(); //in读取信息,堵塞状态
System.out.println("客户收到服务器的回应:" + s);
} catch (Exception e) {
System.out.println("服务器已断开" + e);
}
}
}
服务器端
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server3 {
public static void main(String args[]) {
MyDC mydc = new MyDC();
ServerSocket serverForClient = null;
Socket socketOnServer = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
serverForClient = new ServerSocket(5318);
} catch (IOException e1) {
System.out.println(e1);
}
try {
System.out.println("等待客户呼叫");
socketOnServer = serverForClient.accept(); //堵塞状态,除非有客户呼叫
System.out.println("客户已连接");
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
String leng = in.readUTF(); // in读取信息,堵塞状态
byte ctext[] = new byte[Integer.parseInt(leng)];
for (int i = 0;i<Integer.parseInt(leng);i++) {
String temp = in.readUTF();
ctext[i] = Byte.parseByte(temp);
}
// 获取密钥
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);
/*for (int i = 0; i < ptext.length; i++) {
System.out.print(ptext[i] + ",");
}
*/
System.out.println("");
// 显示明文
String p = new String(ptext,"UTF8");
System.out.println("被解密的后缀表达式:" + p);
System.out.println("计算后缀表达式" + p);
out.writeUTF(mydc.evaluate(p)+"");
} catch (Exception e) {
System.out.println("客户已断开" + e);
}
}
}
实验截图
实验要求
实验原理
实验代码
客户端
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.Socket;
import java.security.Key;
import java.util.Optional;
import java.util.Scanner;
public class Client4 {
public static void main(String args[]) {
MyBC mybc = new MyBC();
Socket mysocket;
DataInputStream in = null;
DataOutputStream out = null;
Scanner scanner = new Scanner(System.in);
String str;
try {
mysocket = new Socket("192.168.188.1", 5318);
System.out.println("客户端启动...");
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
System.out.println("请输入中缀表达式:");
str = scanner.nextLine();
Key_DH.DH("Cpub.dat","Cpri.dat");
FileInputStream fp = new FileInputStream("Cpub.dat");
ObjectInputStream bp = new ObjectInputStream(fp);
Key kp = (Key) bp.readObject();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(kp);
byte[] kb = baos.toByteArray();
out.writeUTF(kb.length + "");
for (int i = 0; i < kb.length; i++) {
out.writeUTF(kb[i] + "");
}
Thread.sleep(1000);
int len = Integer.parseInt(in.readUTF());
byte np[] = new byte[len];
for (int i = 0;i<len;i++) {
String temp = in.readUTF();
np[i] = Byte.parseByte(temp);
}
ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream (np));
Key k2 = (Key)ois.readObject();;
FileOutputStream f2 = new FileOutputStream("Spub.dat");
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(k2);
KeyAgree.DH("Spub.dat","Cpri.dat");
FileInputStream f = new FileInputStream("sb.dat");
byte[] keysb = new byte[24];
f.read(keysb);
System.out.println("公共密钥:");
for (int i = 0;i<24;i++) {
System.out.print(keysb[i]+",");
}
System.out.println("");
SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, k);
mybc.conversion(str);
String str1 = mybc.getMessage();
byte ptext[] = str1.getBytes("UTF-8");
byte ctext[] = cp.doFinal(ptext);
System.out.println("后缀表达式已被加密:");
for (int i = 0; i < ctext.length; i++) {
System.out.print(ctext[i] + ",");
}
System.out.println("");
out.writeUTF(ctext.length + "");
for (int i = 0; i < ctext.length; i++) {
out.writeUTF(ctext[i] + "");
}
String s = in.readUTF(); //in读取信息,堵塞状态
System.out.println("客户收到服务器的回应:" + s);
} catch (Exception e) {
System.out.println("服务器已断开" + e);
}
}
}
服务器端
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Key;
public class Server4 {
public static void main(String args[]) {
MyDC mydc = new MyDC();
ServerSocket serverForClient = null;
Socket socketOnServer = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
serverForClient = new ServerSocket(5318);
} catch (IOException e1) {
System.out.println(e1);
}
try {
System.out.println("等待客户呼叫");
socketOnServer = serverForClient.accept(); //堵塞状态,除非有客户呼叫
System.out.println("客户已连接");
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
Key_DH.DH("Spub.dat","Spri.dat");
int len = Integer.parseInt(in.readUTF());
byte np[] = new byte[len];
for (int i = 0;i<len;i++) {
String temp = in.readUTF();
np[i] = Byte.parseByte(temp);
}
ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream (np));
Key k2 = (Key)ois.readObject();;
FileOutputStream f2 = new FileOutputStream("Cpub.dat");
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(k2);
FileInputStream fp = new FileInputStream("Spub.dat");
ObjectInputStream bp = new ObjectInputStream(fp);
Key kp = (Key) bp.readObject();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(kp);
byte[] kb = baos.toByteArray();
out.writeUTF(kb.length + "");
for (int i = 0; i < kb.length; i++) {
out.writeUTF(kb[i] + "");
}
KeyAgree.DH("Cpub.dat","Spri.dat");
String leng = in.readUTF(); // in读取信息,堵塞状态
byte ctext[] = new byte[Integer.parseInt(leng)];
for (int i = 0;i<Integer.parseInt(leng);i++) {
String temp = in.readUTF();
ctext[i] = Byte.parseByte(temp);
}
// 获取密钥
FileInputStream f = new FileInputStream("sb.dat");
byte[] keysb = new byte[24];
f.read(keysb);
System.out.println("公共密钥:");
for (int i = 0;i<24;i++) {
System.out.print(keysb[i]+",");
}
System.out.println("");
SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
// 解密
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE, k);
byte[] ptext = cp.doFinal(ctext);
System.out.println("");
// 显示明文
String p = new String(ptext,"UTF8");
System.out.println("被解密的后缀表达式:" + p);
System.out.println("计算后缀表达式" + p);
out.writeUTF(mydc.evaluate(p)+"");
} catch (Exception e) {
System.out.println("客户已断开" + e);
}
}
}
实验截图
实验要求
实验代码
客户端
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.Socket;
import java.security.Key;
import java.util.Scanner;
public class Client5 {
public static void main(String args[]) {
MyBC mybc = new MyBC();
Socket mysocket;
DataInputStream in = null;
DataOutputStream out = null;
Scanner scanner = new Scanner(System.in);
String str;
try {
mysocket = new Socket("192.168.188.1", 5318);
System.out.println("客户端启动...");
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
System.out.println("请输入中缀表达式:");
str = scanner.nextLine();
Key_DH.DH("Cpub.dat","Cpri.dat");
FileInputStream fp = new FileInputStream("Cpub.dat");
ObjectInputStream bp = new ObjectInputStream(fp);
Key kp = (Key) bp.readObject();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(kp);
byte[] kb = baos.toByteArray();
out.writeUTF(kb.length + "");
for (int i = 0; i < kb.length; i++) {
out.writeUTF(kb[i] + "");
}
Thread.sleep(500);
int len = Integer.parseInt(in.readUTF());
byte np[] = new byte[len];
for (int i = 0;i<len;i++) {
String temp = in.readUTF();
np[i] = Byte.parseByte(temp);
}
ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream (np));
Key k2 = (Key)ois.readObject();;
FileOutputStream f2 = new FileOutputStream("Spub.dat");
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(k2);
KeyAgree.DH("Spub.dat","Cpri.dat");
FileInputStream f = new FileInputStream("sb.dat");
byte[] keysb = new byte[24];
f.read(keysb);
System.out.println("公共密钥:");
for (int i = 0;i<24;i++) {
System.out.print(keysb[i]+",");
}
System.out.println("");
SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, k);
mybc.conversion(str);
String str1 = mybc.getMessage();
byte ptext[] = str1.getBytes("UTF-8");
String ptextMd5 = DigestPass.DP(str1);
System.out.println("明文的MD5值:"+ptextMd5);
byte ctext[] = cp.doFinal(ptext);
System.out.println("被加密的后缀表达式:");
for (int i = 0; i < ctext.length; i++) {
System.out.print(ctext[i] + ",");
}
System.out.println("");
out.writeUTF(ctext.length + "");
for (int i = 0; i < ctext.length; i++) {
out.writeUTF(ctext[i] + "");
}
out.writeUTF(ptextMd5);
String s = in.readUTF(); //in读取信息,堵塞状态
System.out.println("客户收到服务器的回应:" + s);
} catch (Exception e) {
System.out.println("服务器已断开" + e);
}
}
}
服务器端
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Key;
public class Server5 {
public static void main(String args[]) {
MyDC mydc = new MyDC();
ServerSocket serverForClient = null;
Socket socketOnServer = null;
DataOutputStream out = null;
DataInputStream in = null;
try {
serverForClient = new ServerSocket(5318);
} catch (IOException e1) {
System.out.println(e1);
}
try {
System.out.println("等待客户呼叫");
socketOnServer = serverForClient.accept(); //堵塞状态,除非有客户呼叫
System.out.println("客户已连接");
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
Key_DH.DH("Spub.dat","Spri.dat");
int len = Integer.parseInt(in.readUTF());
byte np[] = new byte[len];
for (int i = 0;i<len;i++) {
String temp = in.readUTF();
np[i] = Byte.parseByte(temp);
}
ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream(np));
Key k2 = (Key)ois.readObject();;
FileOutputStream f2 = new FileOutputStream("Cpub.dat");
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(k2);
FileInputStream fp = new FileInputStream("Spub.dat");
ObjectInputStream bp = new ObjectInputStream(fp);
Key kp = (Key) bp.readObject();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(kp);
byte[] kb = baos.toByteArray();
out.writeUTF(kb.length + "");
for (int i = 0; i < kb.length; i++) {
out.writeUTF(kb[i] + "");
}
KeyAgree.DH("Cpub.dat","Spri.dat");
String leng = in.readUTF(); // in读取信息,堵塞状态
byte ctext[] = new byte[Integer.parseInt(leng)];
for (int i = 0;i<Integer.parseInt(leng);i++) {
String temp = in.readUTF();
ctext[i] = Byte.parseByte(temp);
}
String check = in.readUTF();
// 获取密钥
FileInputStream f = new FileInputStream("sb.dat");
byte[] keysb = new byte[24];
f.read(keysb);
System.out.println("公共密钥:");
for (int i = 0;i<24;i++) {
System.out.print(keysb[i]+",");
}
System.out.println("");
SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
// 解密
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE, k);
byte[] ptext = cp.doFinal(ctext);
System.out.println("");
// 显示明文
String p = new String(ptext, "UTF8");
String pMd5 = DigestPass.DP(p);
System.out.println("被解密明文的MD5值:"+pMd5);
if (pMd5.equals(check)){
System.out.println("和客户端的MD5值一致");
System.out.println("计算后缀表达式" + p);
out.writeUTF(mydc.evaluate(p)+"");
}
else {
System.out.println("警告:和客户端的MD5值不一致!");
}
} catch (Exception e) {
System.out.println("客户已断开" + e);
}
}
}
实验截图
此次实验的内容主要是是网络编程,同时结合密码学算法。在这次实验之前,虽然有学过Java网络编程理论内容,但真正自己动手编程时,发现并不太理解如何实现客户端和服务器,在和结对小伙变一起复习网络编程和密码学算法相关内容后,我们参考书上代码和Java 密码学算法,最终完成了实验,在这个过程中,我们复习了相关知识,也学到了很多信的内容。
步骤 | 耗时 | 百分比 |
---|---|---|
需求分析 | 50min | 20% |
设计 | 20min | 8% |
代码实现 | 100min | 42% |
测试 | 20min | 8% |
分析总结 | 50min | 22% |
Java 密码学算法
2016-2017-2 《Java 程序设计》课堂实践项目
2017-2018-2 20165318 实验五《网络编程与安全》实验报告
标签:.com ade 否则 int() 实验代码 strong post 技术分享 remove
原文地址:https://www.cnblogs.com/sunxiaoxuan/p/9102965.html