标签:default 算法 后缀表达式求值 param hash函数 ini ant new t +=
1、实验要求
两人一组结对编程:
import javax.xml.bind.annotation.XmlType;
import java.lang.Integer;
import java.util.StringTokenizer;
import java.util.Stack;
public class MyDC
{
/** constant for addition symbol */
private final String ADD="+";
/** constant for subtraction symbol */
private final String SUBTRACT="-";
/** constant for multiplication symbol */
private final String MULTIPLY="*";
/** constant for division symbol */
private final String DIVIDE="/";
/** the stack */
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();
//如果是运算符,调用isOperator
if (isOperator(token)) {
//从栈中弹出操作数2
op2 = stack.pop();
//从栈中弹出操作数1
op1 = stack.pop();
//根据运算符和两个操作数调用evalSingleOp计算result;
result = evalSingleOp(token, op1, op2);
//计算result入栈;
stack.push(result);
} else//如果是操作数
{
stack.push(Integer.parseInt(token));
//操作数入栈;
}
}
return result;
}
private boolean isOperator(String token)
{
return(token.equals("+")||token.equals("-")||
token.equals("*")||token.equals("/"));
}
private int evalSingleOp(String 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;
default:
break;
}
return result;
}
}
MyBC:
import java.util.StringTokenizer;
import java.util.Stack;
public class MyBC{
private Stack<Character> stack1;
public char Precede(char a,char b)
{
if(a=='#')
if(b!='#')
return '<';
else
return '=';
if(a==')')
return '>';
if(a=='(')
if(b!=')')
return '<';
else
return '=';
if(a=='/'||a=='*')
if(b!='(')
return '>';
else
return '<';
if(a=='-'||a=='+')
if(b!='*'&&b!='/'&&b!='(')
return '>';
else
return '<';
return '>';
}
public MyBC() {
stack1 = new Stack<Character>();
stack1.push('#');
}
public String turn(String expr) {
int result = 0;
String token;
char topelem,optr;
char[] exper1 = new char[100];
int i = 0;
StringTokenizer tokenizer = new StringTokenizer (expr);
/*while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}*/
while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();
//如果是运算符,调用isOperator
if (isOperator(token))
{
//调用Precede比较优先级
topelem=stack1.peek();
optr = token.charAt(0);
if(Precede(topelem,optr)=='<')
{
stack1.push(optr);
}
else if(Precede(topelem,optr)=='=')
{
/*if(optr==')'){
optr=stack1.pop();
while(optr!='('){
exper1[i++]=optr;
exper1[i++]=' ';
optr=stack1.pop();
}
}*/
optr =stack1.pop();
exper1[i++] = optr;
exper1[i++] = ' ';
}
else if(Precede(topelem,optr)=='>')
{
optr =stack1.pop();
//从运算符栈中退出栈顶元素并放入后缀表达式exper1
exper1[i++] = optr;
exper1[i++] = ' ';
}
}//如果是(则入栈
else if(token.equals("(")) {
optr = token.charAt(0);
stack1.push(optr);
}//如果是)则退栈直到出现第一个(
else if(token.equals(")")) {
optr = stack1.pop();
while(optr!='(')
{
exper1[i++] = optr;
exper1[i++] = ' ';
optr = stack1.pop();
}
}
else//如果是操作数
//操作数放入后缀表达式exper1
{
optr = token.charAt(0);
//System.out.println(optr);
exper1[i++]=optr;
exper1[i++] = ' ';
}
}
while(!stack1.isEmpty())
{
optr = stack1.pop();
if(optr!='#'){
exper1[i++] = optr;
exper1[i++] = ' ';
}
}
//System.out.println(exper1);
return ToString(exper1);
}
//@Override
private boolean isOperator(String token)
{
return (token.equals("+") || token.equals("-") ||token.equals("*") || token.equals("/") );
}
public static String ToString(char[] exper1){
int length = exper1.length;
String str=" ";
for(int i=0;i<length;i++)
{
str=str+exper1[i];
}
//System.out.println(str);
return str;
}
/*public static void main(String[] args) {
String pp=null;
MyBC turner = new MyBC();
pp=turner.turn("( 1 + 2 ) * ( ( 8 - 2 ) / ( 7 - 4 ) )");
System.out.println(pp);
}*/
}
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client {
public static final String IP_ADDR = "127.0.0.1";//服务器地址
public static final int PORT = 12345;//服务器端口号
public static void main(String[] args) {
System.out.println("客户端启动...");
System.out.println("当接收到服务器端字符为 \"OK\" 的时候, 客户端将终止\n");
while (true) {
Socket socket = null;
try {
//创建一个流套接字并将其连接到指定主机上的指定端口号
socket = new Socket(IP_ADDR, PORT);
//读取服务器端数据
DataInputStream input = new DataInputStream(socket.getInputStream());
//向服务器端发送数据
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
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);
out.writeUTF(str2);
String ret = input.readUTF();
System.out.println("服务器端返回过来的是: " + ret);
// 如接收到 "OK" 则断开连接
/*if ("OK".equals(ret)) {
System.out.println("客户端将关闭连接");
Thread.sleep(500);
break;
}*/
out.close();
input.close();
} catch (Exception e) {
System.out.println("客户端异常:" + e.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
System.out.println("客户端 finally 异常:" + e.getMessage());
}
}
}
}
}
}
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static final int PORT = 12345;//监听的端口号
public static void main(String[] args) {
System.out.println("服务器启动...\n");
Server server = new Server();
server.init();
}
public void init() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
// 一旦有堵塞, 则表示服务器与客户端获得了连接
Socket client = serverSocket.accept();
// 处理这次连接
new HandlerThread(client);
}
} catch (Exception e) {
System.out.println("服务器异常: " + e.getMessage());
}
}
private class HandlerThread implements Runnable {
private Socket socket;
public HandlerThread(Socket client) {
socket = client;
new Thread(this).start();
}
public void run() {
try {
// 读取客户端数据
DataInputStream input = new DataInputStream(socket.getInputStream());
String clientInputStr = input.readUTF();//这里要注意和客户端输出流的写方法对应,否则会抛 EOFException
// 处理客户端数据
System.out.println("客户端发过来的内容:" + clientInputStr);
MyDC evalute = new MyDC();
int result = evalute.evaluate(clientInputStr);
// 向客户端回复信息
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
System.out.print("计算结果:\t");
// 发送键盘输入的一行
//String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
out.writeUTF(String.valueOf(result));
out.close();
input.close();
} catch (Exception e) {
System.out.println("服务器 run 异常: " + e.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
socket = null;
System.out.println("服务端 finally 异常:" + e.getMessage());
}
}
}
}
}
}
加密结对编程:1人负责客户端,一人负责服务器
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client2 {
public static final String IP_ADDR = "127.0.0.1";//服务器地址
public static final int PORT = 12345;//服务器端口号
public static void main(String[] args) {
System.out.println("客户端启动...");
System.out.println("当接收到服务器端字符为 \"OK\" 的时候, 客户端将终止\n");
while (true) {
Socket socket = null;
try {
//创建一个流套接字并将其连接到指定主机上的指定端口号
socket = new Socket(IP_ADDR, PORT);
//读取服务器端数据
DataInputStream input = new DataInputStream(socket.getInputStream());
//向服务器端发送数据
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
System.out.print("请输入: \t");
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
MyBC turner = new MyBC();
Skey_DES skey_des = new Skey_DES();
skey_des.key_DES();
Skey_kb skey_kb = new Skey_kb();
skey_kb.key();
/*产生密钥*/
SEnc sEnc = new SEnc();
String str1 = turner.turn(str);
int length=0,i=0;
while(str1.charAt(i)!='\0'){
length++;
i++;
}
String str2 = str1.substring(1,length-1);
out.writeUTF(str2);
String ret = input.readUTF();
System.out.println("服务器端返回过来的是: " + ret);
// 如接收到 "OK" 则断开连接
/*if ("OK".equals(ret)) {
System.out.println("客户端将关闭连接");
Thread.sleep(500);
break;
}*/
out.close();
input.close();
} catch (Exception e) {
System.out.println("客户端异常:" + e.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
System.out.println("客户端 finally 异常:" + e.getMessage());
}
}
}
}
}
}
服务器
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server2 {
public static final int PORT = 12345;//监听的端口号
public static void main(String[] args) {
System.out.println("服务器启动...\n");
Server server = new Server();
server.init();
}
public void init() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
// 一旦有堵塞, 则表示服务器与客户端获得了连接
Socket client = serverSocket.accept();
// 处理这次连接
new HandlerThread(client);
}
} catch (Exception e) {
System.out.println("服务器异常: " + e.getMessage());
}
}
private class HandlerThread implements Runnable {
private Socket socket;
public HandlerThread(Socket client) {
socket = client;
new Thread(this).start();
}
public void run() {
try {
// 读取客户端数据
DataInputStream input = new DataInputStream(socket.getInputStream());
String clientInputStr = input.readUTF();//这里要注意和客户端输出流的写方法对应,否则会抛 EOFException
// 处理客户端数据
System.out.println("客户端发过来的内容:" + clientInputStr);
MyDC evalute = new MyDC();
SDec sDec = new SDec();
int result = evalute.evaluate(clientInputStr);
// 向客户端回复信息
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
System.out.print("计算结果:\t");
// 发送键盘输入的一行
//String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
out.writeUTF(String.valueOf(result));
out.close();
input.close();
} catch (Exception e) {
System.out.println("服务器 run 异常: " + e.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
socket = null;
System.out.println("服务端 finally 异常:" + e.getMessage());
}
}
}
}
}
}
运行截图
密钥分发结对编程:1人负责客户端,一人负责服务器
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{
private 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
};
private static final BigInteger skip1024Modulus = new BigInteger(1, skip1024ModulusBytes);
private static final BigInteger skip1024Base = BigInteger.valueOf(2);
public static void fun(String s1,String s2) 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(s1);
ObjectOutputStream b1=new ObjectOutputStream(f1);
b1.writeObject(pbk);
// 保存私钥
FileOutputStream f2=new FileOutputStream(s2);
ObjectOutputStream b2=new ObjectOutputStream(f2);
b2.writeObject(prk);
}
}
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_Agree{
public static void main(String args[ ]) throws Exception{
// 读取对方的DH公钥
FileInputStream f1=new FileInputStream(args[0]);
ObjectInputStream b1=new ObjectInputStream(f1);
PublicKey pbk=(PublicKey)b1.readObject( );
//读取自己的DH私钥
FileInputStream f2=new FileInputStream(args[1]);
ObjectInputStream b2=new ObjectInputStream(f2);
PrivateKey prk=(PrivateKey)b2.readObject( );
// 执行密钥协定
KeyAgreement ka=KeyAgreement.getInstance("DH");
ka.init(prk);
ka.doPhase(pbk,true);
//生成共享信息
byte[ ] sb=ka.generateSecret();
for(int i=0;i<sb.length;i++){
System.out.print(sb[i]+",");
}
SecretKeySpec k=new SecretKeySpec(sb,"DESede");
}
public static void fun(String s, String s1) {
}
}
完整性校验结对编程:1人负责客户端,一人负责服务器
import java.io.*;
import java.net.*;
import java.applet.Applet;
import java.security.MessageDigest;
public class Server3 {
public static void main(String args[]) {
MyDC evalute = new MyDC();
SDec sDec = new SDec();
try {
ServerSocket server = null;
try {
server = new ServerSocket(4700);
//创建一个ServerSocket在端口4700监听客户请求
} catch (Exception e) {
System.out.println("can not listen to:" + e);
//出错,打印出错信息
}
Socket socket = null;
try {
socket = server.accept();
//使用accept()阻塞等待客户请求,有客户
//请求到来则产生一个Socket对象,并继续执行
} catch (Exception e) {
System.out.println("Error." + e);
//出错,打印出错信息
}
String line;
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输入流,并构造相应的BufferedReader对象
PrintWriter os = new PrintWriter(socket.getOutputStream());
//由Socket对象得到输出流,并构造PrintWriter对象
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
//由系统标准输入设备构造BufferedReader对象
//使用Hash函数检测明文完整性
String x = sin.readLine();
MessageDigest m2 = MessageDigest.getInstance("MD5");
//使用MD5算法返回实现指定摘要算法的 MessageDigest对象
m2.update(x.getBytes());
byte a[] = m2.digest();
String result = "";
for (int i = 0; i < a.length; i++) {
result += Integer.toHexString((0x000000ff & a[i]) | 0xffffff00).substring(6);
}
System.out.println(result);
String match = is.readLine();
if (match.equals(result)) {
System.out.println("匹配成功");
}
System.out.println("Client:" + is.readLine());
//在标准输出上打印从客户端读入的字符串
line = sin.readLine();
//从标准输入读入一字符串
while (!line.equals("bye")) {
//如果该字符串为 "bye",则停止循环
os.println(evalute.evaluate(line));
//向客户端输出该字符串
os.flush();
//刷新输出流,使Client马上收到该字符串
System.out.println("Server:" + evalute.evaluate(line));
//在系统标准输出上打印读入的字符串
System.out.println("Client:" + is.readLine());
//从Client读入一字符串,并打印到标准输出上
line = sin.readLine();
//从系统标准输入读入一字符串
} //继续循环
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
server.close(); //关闭ServerSocket
} catch (Exception e) {
System.out.println("Error:" + e);
//出错,打印出错信息
}
}
}
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
public class Client3 {
public static void main(String args[]) throws Exception {
MyBC turner = new MyBC();
Skey_DES skey_des = new Skey_DES();
skey_des.key_DES();
Skey_kb skey_kb = new Skey_kb();
skey_kb.key();
/*产生密钥*/
SEnc sEnc = new SEnc();
try {
Socket socket = new Socket("127.0.0.1", 4700);
//向本机的4700端口发出客户请求
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
//由系统标准输入设备构造BufferedReader对象
PrintWriter os = new PrintWriter(socket.getOutputStream());
//由Socket对象得到输出流,并构造PrintWriter对象
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输入流,并构造相应的BufferedReader对象
String readline;
readline =sin.readLine();
//从系统标准输入读入一字符串
String x = readline;
// 将客户端明文的Hash值传送给服务器
MessageDigest m2 = MessageDigest.getInstance("MD5");
m2.update(x.getBytes());
byte a[] = m2.digest();
String result = "";
for (int i = 0; i < a.length; i++) {
result += Integer.toHexString((0x000000ff & a[i]) | 0xffffff00).substring(6);
}
System.out.println("明文MD5值为:" + result);
os.println(result);//通过网络将明文的Hash函数值传送到服务器
// String str = is.readLine();// 从网络输入流读取结果
System.out.println("从服务器接收到的结果为:" + result); // 输出服务器返回的结果
while (!readline.equals("bye")) {
//若从标准输入读入的字符串为 "bye"则停止循环
readline = SEnc.Enc(turner.turn(readline));
os.println(readline);
/*把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES加密后通过网络发送给服务器*/
//将从系统标准输入读入的字符串输出到Server
os.flush();
//刷新输出流,使Server马上收到该字符串
System.out.println("Client:" + readline);
//在系统标准输出上打印读入的字符串
System.out.println("Server:" + is.readLine());
//从Server读入一字符串,并打印到标准输出上
readline = sin.readLine(); //从系统标准输入读入一字符串
} //继续循环
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
} catch (Exception e) {
System.out.println("Error" + e); //出错,则打印出错信息
}
}
}
标签:default 算法 后缀表达式求值 param hash函数 ini ant new t +=
原文地址:https://www.cnblogs.com/Hf-Hf/p/10952110.html