实验内容
- 实验五 网络编程与安全-1
两人一组结对编程:
- 参考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA
- 结对实现中缀表达式转后缀表达式的功能 MyBC.java
- 结对实现从上面功能中获取的表达式中实现后缀表达式求值的功能,调用MyDC.java
- 上传测试代码运行结果截图和码云链接
首先实现MyBC.java(后缀转中缀)
public class MyBC { public static String toPostfix(String expr){ MyStack<String> stack = new MyStack<>(expr.length());//expr抓取字段() String postfix = "";//赋空值 int i = 0; while(i<expr.length()){// char ch = expr.charAt(i);//取第i个字符 switch (ch){ case ‘+‘: case ‘-‘:while(!stack.isEmpty() && !stack.get().equals("(")) postfix += stack.pop(); //postfix += " "; stack.push(ch + ""); i++; break; case ‘*‘: case ‘/‘:while (!stack.isEmpty() && (stack.get().equals("*")||stack.get().equals("/"))) postfix += stack.pop(); //postfix += " "; stack.push(ch + ""); i++; break; case ‘(‘:stack.push(ch + ""); i++; break; case ‘)‘:String out = stack.pop(); while(out!=null && !out.equals("(")){ postfix += out; out = stack.pop(); //postfix += " "; } i++; break; default:while(i < expr.length() && ch>=‘0‘ && ch<=‘9‘){ postfix += ch; i++; if(i<expr.length()) ch = expr.charAt(i); } postfix += " "; } } while (!stack.isEmpty()) postfix += stack.pop(); return postfix; } }
然后加入建立栈的MyStack.java
interface SStack<T> {//栈接口,栈数据抽象类型
boolean isEmpty();//判断是否空栈
void push(T x);//元素x入栈
T pop();//出栈,返回当前栈顶元素
T get();//取栈顶元素
}
public class MyStack<T> implements SStack<T> {
private Object element[];//储存数据数组
private int top;//栈顶元素下标
public MyStack(int size){//容纳大小为size的栈
this.element = new Object[Math.abs(size)];
this.top = -1;
}
public MyStack() {
this(64);//栈大小为64
}
public boolean isEmpty() {
return this.top == -1;//空栈栈顶元素为-1
}
public void push(T x) {//元素x入栈
if(x==null)
return;//栈空时不如栈
if(this.top == element.length-1){//栈满时,申请更大空间
Object[] temp = this.element;
this.element = new Object[temp.length*2];
for(int i = 0; i < temp.length; i++)
this.element[i] = temp[i];
}
this.top++;
this.element[this.top] = x;
}
public T pop() {
return this.top==-1 ? null:(T)this.element[this.top--];//弹栈
}
public T get() {
return this.top==-1 ? null:(T)this.element[this.top];//取元素
}
}
最后不要忘记加入MyDC.java(求后缀表达式的值)
import java.util.Stack;
/**
* Created by dell on 2017/5/24.
*/
public class MyDC {
/** constant for addition symbol */
private final char ADD = ‘+‘;
/** constant for subtraction symbol */
private final char SUBTRACT = ‘-‘;
/** constant for multiplication symbol */
private final char MULTIPLY = ‘*‘;
/** constant for division symbol */
private final char DIVIDE = ‘/‘;
public int value(String postfix){
Stack<Integer> stack = new Stack();
int i = 0, result = 0;
while(i < postfix.length()){
char ch = postfix.charAt(i);
if(ch>=‘0‘ && ch<=‘9‘){
result = 0;
while(ch!=‘ ‘){
result = result*10 + Integer.parseInt(ch+"");
i++;
ch = postfix.charAt(i);
}
i++;
stack.push(new Integer(result));
}
else{
int y = stack.pop().intValue();
int x = stack.pop().intValue();
switch (ch){
case ADD:
result = x + y;
break;
case SUBTRACT:
result = x - y;
break;
case MULTIPLY:
result = x * y;
break;
case DIVIDE:
result = x / y;
}
stack.push(new Integer(result));
i++;
}
}
return stack.pop().intValue();
}
}
到此,已经把所以代码编写完成,最后加入测试代码
import java.util.Scanner;
public class MyDCtest {
public static void main(String [] args) {
String expression;
int result;
try
{
Scanner in = new Scanner(System.in);
MyDC evaluator = new MyDC();
System.out.println ("Enter a valid infix expression: ");
expression = in.nextLine();
String postfix = MyBC.toPostfix(expression);
System.out.println ("The postfix expression is :" + postfix);
result = evaluator.value (postfix);
System.out.println ("That expression equals :" + result);
}
catch (Exception IOException)
{
System.out.println("Input exception reported");
}
}
}
之后运行MyDCtest就可以了
实验五 网络编程与安全-2
结对编程:一人负责客户端,一人负责服务器
- 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能
转化为后缀表达式,把后缀表达式通过网络发送给服务器
- 服务器接收到后缀表达式,调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
我在本实验中负责服务端;
编写服务端代码Service.java
import java.net.*;
import java.io.*;
public class Service{
public static void main(String srgs[]) {
ServerSocket sc = null;
Socket socket=null;
try {
MyDC evaluator = new MyDC();
sc= new ServerSocket(2018);//创建服务器套接字
System.out.println("端口号:" + sc.getLocalPort());
System.out.println("服务器已经启动...");
socket = sc.accept(); //等待客户端连接
System.out.println("已经建立连接");
//获得网络输入流对象的引用
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
////获得网络输出流对象的引用
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
String aline=in.readLine();//读取客户端传送来的数据
System.out.println("从客户端接收到信息为:"+aline); //通过网络输出流返回结果给客户端
int result = evaluator.value(aline);
out.println("Echo:" + result);
out.close();
in.close();
sc.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
之后运行Service.java
实验五 网络编程与安全-3
加密结对编程:1人负责客户端,一人负责服务器
- 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密后通过网络把密文发送给服务器
- 服务器接收到后缀表达式表达式后,进行解密(和客户端协商密钥,可以用数组保存),然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
在本任务中我负责服务端,但是因为我在这个代码的基础上做了后两个实验,所以代码我贴在了检查点5里。
实验五 网络编程与安全-4
密钥分发结对编程:1人负责客户端,一人负责服务器
- 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文发送给服务器
- 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
- 服务器接收到后缀表达式表达式后,进行解密,然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
在这个检查点里添加了DH算法的密钥Key_DH.java
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
};
// The SKIP 1024 bit modulus
private static final BigInteger skip1024Modulus
= new BigInteger(1, skip1024ModulusBytes);
// The base used with the SKIP 1024 bit modulus
private 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);
}
}
接着加入Key_Agree.java
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");
}
}
实验五 网络编程与安全-5
完整性校验结对编程:1人负责客户端,一人负责服务器
- 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文和明文的MD5値发送给服务器
- 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
- 服务器接收到后缀表达式表达式后,进行解密,解密后计算明文的MD5值,和客户端传来的MD5进行比较,一致则调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
我负责服务器端
import java.net.*;
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;
public class ServiceDecode {
public static void main(String args[]) throws Exception {
ServerSocket link = null;
Socket socket = null;
try {
link = new ServerSocket(2018);// 创建服务器套接字
System.out.println("端口号:" + link.getLocalPort());
System.out.println("服务器已经启动...");
socket = link.accept(); // 等待客户端连接
System.out.println("已经建立连接");
//获得网络输入流对象的引用
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//获得网络输出流对象的引用
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
// 使用服务器端RSA的私钥对DES的密钥进行解密
String line = in.readLine();
BigInteger cipher = new BigInteger(line);
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();//mod n
BigInteger m = cipher.modPow(d, n);//m=d (mod n)
System.out.println("d= " + d);
System.out.println("n= " + n);
System.out.println("m= " + m);
byte[] keykb = m.toByteArray();
// 使用DES对密文进行解密
String readline = in.readLine();//读取客户端传送来的数据
FileInputStream f2 = new FileInputStream("keykb1.dat");
int num2 = f2.available();
byte[] ctext = parseHexStr2Byte(readline);
Key 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); //打印解密结果
// 使用Hash函数检测明文完整性
String aline3 = in.readLine();
String x = p;
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);
if (aline3.equals(result)) {
System.out.println("匹配成功");
}
MyDC evaluator = new MyDC();
int _result = evaluator.value(p);
out.println("Echo:" + _result);
out.close();
in.close();
link.close();
} catch (Exception e) {
System.out.println(e);
}
}
//二进制转换成十六进制,防止byte[]数字转换成string类型时造成的数据损失
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = ‘0‘ + hex;
}
sb.append(hex.toUpperCase());//将字符串中的小写字母转换成大写字母,然后加在字符串上
}
return sb.toString();
}
//将十六进制转换为二进制
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1),16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
遇到的问题及方法
解决方法:将public去掉解决
实验感想
- 这个实验大部分我都不会做,基本都是看学姐的代码然后自己争取看懂
- 在做检查点一时,学会了栈的建立,当时是每一句都百度,但是其实就发现是常规方法,也算是学习了。
原文地址:https://www.cnblogs.com/mushroomissmart/p/9123497.html
时间: 2024-10-03 18:43:33