2018-2019-2 20175105王鑫浩 实验五《网络编程与安全》实验报告
一、实验报告封面
-
课程:Java程序设计 班级:1751 班 姓名:王鑫浩 学号:20175105
-
指导教师:娄嘉鹏
-
实验日期:2019年5月29日
-
实验序号:实验五
-
实验名称:网络编程与安全
二、实验内容
检查点一:
两人一组结对编程:
0. 参考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA
- 结对实现中缀表达式转后缀表达式的功能 MyBC.java
- 结对实现从上面功能中获取的表达式中实现后缀表达式求值的功能,调用MyDC.java
- 上传测试代码运行结果截图和码云链接
编程思路:
由中缀式求得后缀式可以使用栈,伪代码如下:
-
设立一个栈,存放运算符,首先栈为空;
-
从左到右扫描中缀式,若遇到操作数,直接输出,并输出一个空格作为两个操作数的分隔符;
-
若遇到运算符,则与栈顶比较,比栈顶级别高则进栈,否则退出栈顶元素并输出,然后输出一个空格作分隔符;
-
若遇到左括号,进栈;若遇到右括号,则一直退栈输出,直到退到左括号止。
-
当栈变成空时,输出的结果即为后缀表达式。
算符优先法求解表达式:
-
步骤1:建立符号运算的优先级关系表
-
步骤2 :
** (1) 设操作数栈OPND,置空;运算符栈OPTR,最低符号#压进OPTR;
** (2) 读入字符C,C若是操作数, 进OPND;若是运算符,与OPTR栈顶元素(A)比较,根据算符优先级,决定如何处理:
*** A<C, C压入OPTR栈;
*** A=C, A从OPTR出栈;
*** A>C,A出栈,从OPND依次弹出两个操作数y、x, 计算Z=x A y,Z压入OPND栈。C压进OPTR.
(3) 重复(2),直至表达式结束。
实验代码
MyBC.java
import java.util.Stack;
public class MyBC {
static Stack<Character> op = new Stack<>();
public static String getrp(String s){
char[] arr = s.toCharArray();
int len = arr.length;
String out = "";
for(int i =0;i<len;i++){
char ch = arr[i];
if(ch == ' ') continue;
if(ch>='0'&&ch<='9'){
out +=ch;
continue;
}
if(ch =='(') op.push(ch);
if(ch == '+'|| ch=='-'){
while(!op.empty()&&(op.peek()!='('))
out +=op.pop();
op.push(ch);
continue;
}
if(ch=='*'||ch=='/'){
while(!op.empty()&&(op.peek()=='*'||op.peek()=='/'))
out+=op.pop();
op.push(ch);
continue;
}
if(ch == ')'){
while(!op.empty()&&op.peek()!='(')
out += op.pop();
op.pop();
continue;
}
}
while(!op.empty()) out += op.pop();
return out;
}
}
MyDC.java
import java.util.Stack;
public class MyDC {
static Stack<Character> op = new Stack<>();
public static Float getv(char op, Float f1, Float f2) {
if (op == '+') {
return f2 + f1;
} else if (op == '-') {
return f2 - f1;
} else if (op == '*') {
return f2 * f1;
} else if (op == '/') {
return f2 / f1;
} else {
return Float.valueOf(-0);
}
}
public static float calrp(String rp) {
Stack<Float> v = new Stack<>();
char[] arr = rp.toCharArray();
int len = arr.length;
for (int i = 0; i < len; i++) {
Character ch = arr[i];
if (ch >= '0' && ch <= '9') {
v.push(Float.valueOf(ch - '0'));
} else {
v.push(getv(ch, v.pop(), v.pop()));
}
}
return v.pop();
}
}
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("请输入运算式:");
String s = in.nextLine();
String s2 = MyBC.getrp(s);
System.out.println("转换为后缀表达式:"+s2);
System.out.println(MyDC.calrp(s2));
}
}
运行效果
检查点二:
结对编程:
1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式通过网络发送给服务器
- 服务器接收到后缀表达式,调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
编写思路
1.利用教材上学到的知识编写服务器端与客户端链接代码
2.通过服务器端与客户端调用MyDC与MyBC
编写代码
Client.java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.Key;
import java.util.Scanner;
import java.net.*;
public class Client {
// 搭建客户端
public static void main(String[] args) throws IOException {
try {
// 1、创建客户端Socket,指定服务器地址和端口
//下面是你要传输到另一台电脑的IP地址和端口
Socket socket = new Socket("192.168.56.1", 5209);
System.out.println("客户端启动成功");
// 2、获取输出流,向服务器端发送信息
// 向本机的52000端口发出客户请求
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 由系统标准输入设备构造BufferedReader对象
PrintWriter write = new PrintWriter(socket.getOutputStream());
// 由Socket对象得到输出流,并构造PrintWriter对象
//3、获取输入流,并读取服务器端的响应信息
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 由Socket对象得到输入流,并构造相应的BufferedReader对象
String readline;
readline = br.readLine(); // 从系统标准输入读入一字符串
readline = MyBC.getrp(readline);
while (!readline.equals("end")) {
// 若从标准输入读入的字符串为 "end"则停止循环
write.println(readline);
// 将从系统标准输入读入的字符串输出到Server
write.flush();
// 刷新输出流,使Server马上收到该字符串
System.out.println("客户:" + readline);
// 在系统标准输出上打印读入的字符串
System.out.println("服务:" + in.readLine());
// 从Server读入一字符串,并打印到标准输出上
readline = br.readLine(); // 从系统标准输入读入一字符串
} // 继续循环
//4、关闭资源
write.close(); // 关闭Socket输出流
in.close(); // 关闭Socket输入流
socket.close(); // 关闭Socket
} catch (Exception e) {
System.out.println("can not listen to:" + e);// 出错,打印出错信息
}
}
}
Service.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Service {
//搭建服务器端
public static void main(String[] args) throws IOException{
Service socketService = new Service();
//1、a)创建一个服务器端,即Service
socketService.oneServer();
}
public void oneServer(){
try{
ServerSocket server=null;
try{
//下面是端口,端口可以和客户端代码里面的端口一样
server=new ServerSocket(5209);
//b)指定绑定的端口,并监听此端口。
System.out.println("服务器启动成功");
//创建一个ServerSocket在端口5209监听客户请求
}catch(Exception e) {
System.out.println("没有启动监听:"+e);
//出错,打印出错信息
}
Socket socket=null;
try{
socket=server.accept();
//2、调用accept()方法开始监听,等待客户端的连接
//使用accept()阻塞等待客户请求,有客户
//请求到来则产生一个Socket对象,并继续执行
}catch(Exception e) {
System.out.println("Error."+e);
//出错,打印出错信息
}
//3、获取输入流,并读取客户端信息
String line;
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输入流,并构造相应的BufferedReader对象
PrintWriter writer=new PrintWriter(socket.getOutputStream());
//由Socket对象得到输出流,并构造PrintWriter对象
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//由系统标准输入设备构造BufferedReader对象
Float m1=MyDC.calrp(in.readLine());
System.out.println("Client:"+m1);
//在标准输出上打印从客户端读入的字符串
line = m1.toString();
//从标准输入读入一字符串
//4、获取输出流,响应客户端的请求
while(!line.equals("end")){
//如果该字符串为 "bye",则停止循环
writer.println(line);
//向客户端输出该字符串
writer.flush();
//刷新输出流,使Client马上收到该字符串
System.out.println("服务:"+line);
//在系统标准输出上打印读入的字符串
System.out.println("客户:"+in.readLine());
//从Client读入一字符串,并打印到标准输出上
line=br.readLine();
//从系统标准输入读入一字符串
} //继续循环
//5、关闭资源
writer.close(); //关闭Socket输出流
in.close(); //关闭Socket输入流
socket.close(); //关闭Socket
server.close(); //关闭ServerSocket
}catch(Exception e) {//出错,打印出错信息
System.out.println("Error."+e);
}
}
}
注:运行时先运行服务器端,再运行客户端,在客户端输入表达式。
运行效果
检查点三:
结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密后通过网络把密文发送给服务器
- 服务器接收到后缀表达式表达式后,进行解密(和客户端协商密钥,可以用数组保存),然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
编写思路
1.编写AES加密算法,先产生子密钥,然后调用java.security包
编写代码
Skey_AES.java
import java.io.*;
import javax.crypto.*;
public class Skey_AES{
public static void main(String args[]) throws Exception{
KeyGenerator kg=KeyGenerator.getInstance("AES");
kg.init(128);
SecretKey k=kg.generateKey( );
FileOutputStream f=new FileOutputStream("key1.dat");
ObjectOutputStream b=new ObjectOutputStream(f);
b.writeObject(k);
}
}
Encoder.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Scanner;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Encoder {
public static String AESEncode(String encodeRules,String content){
try {
KeyGenerator keygen=KeyGenerator.getInstance("AES");
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
SecretKey original_key=keygen.generateKey();
byte [] raw=original_key.getEncoded();
SecretKey key=new SecretKeySpec(raw, "AES");
Cipher cipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte [] byte_encode=content.getBytes("utf-8");
byte [] byte_AES=cipher.doFinal(byte_encode);
return AES_encode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static String AESDncode(String encodeRules,String content){
try {
KeyGenerator keygen=KeyGenerator.getInstance("AES");
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
SecretKey original_key=keygen.generateKey();
byte [] raw=original_key.getEncoded();
SecretKey key=new SecretKeySpec(raw, "AES");
Cipher cipher=Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte [] byte_content= new BASE64Decoder().decodeBuffer(content);
byte [] byte_decode=cipher.doFinal(byte_content);
String AES_decode=new String(byte_decode,"utf-8");
return AES_decode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
}
Client.java
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.Scanner;
public class Client {
public static void main(String args[]) throws Exception {
String key = "";
int n = -1;
byte[] a = new byte[128];
try {
File f = new File("key1.dat");
InputStream in = new FileInputStream(f);
while ((n = in.read(a, 0, 100)) != -1) {
key = key + new String(a, 0, n);
}
in.close();
} catch (IOException e) {
System.out.println("File read Error" + e);
}
Socket mysocket;
DataInputStream in = null;
DataOutputStream out = null;
System.out.println("客户端连接成功:");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();//输入算式
str = MyBC.getrp(str);
String secret=Encoder.AESEncode(key,str);//客户端进行加密
System.out.println("已加密:"+secret);
try {
mysocket = new Socket("127.1.0.0", 2010);
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
out.writeUTF(key);
out.writeUTF(secret);
String s = in.readUTF(); //in读取信息,堵塞状态
System.out.println("客户收到服务器的回答:" + s);
Thread.sleep(500);
} catch (Exception e) {
System.out.println("服务器已断开" + e);
}
}
}
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main (String args[]) throws Exception {
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 key = in.readUTF();
String s=in.readUTF(); // in读取信息,堵塞状态
System.out.println("服务器收到的信息:"+s);
String clear=Encoder.AESDncode(key,s);
System.out.println("解密后:"+clear);
float answer=MyDC.calrp(clear);
out.writeUTF(answer+"");
Thread.sleep(500);
}
catch(Exception e) {
System.out.println("客户已断开"+e);
}
}
}
运行效果
检查点四:
结对编程:
1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文发送给服务器
- 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
- 服务器接收到后缀表达式表达式后,进行解密,然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
编写代码
AtoB.java
public class AtoB {
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;
}
}
BtoA.java
public class BtoA {
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();
}
}
Agree.java
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Agree {
public static SecretKeySpec createKey(String inpub,String inpri) throws Exception{
String mode = "AES";
//通过命令行参数传入公钥和私钥文件名,第一个命令行参数为对方的公钥文件名,第二个命令行参数为自己的私钥文件名。
FileInputStream f1 = new FileInputStream(inpub);
ObjectInputStream b1 = new ObjectInputStream(f1);
PublicKey pbk = (PublicKey)b1.readObject();
FileInputStream f2 = new FileInputStream(inpri);
ObjectInputStream b2 = new ObjectInputStream(f2);
PrivateKey prk = (PrivateKey) b2.readObject();
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.init(prk);
ka.doPhase(pbk,true);
byte[] s=ka.generateSecret();
byte [] sb = new byte[24];
for(int i=0;i<24;i++){
sb[i]=s[i];
}
System.out.println("客户端与用户端的信息为:");
for(int i=0;i<sb.length;i++){
System.out.print(sb[i]+" ");
}
System.out.println();
SecretKeySpec k=new SecretKeySpec(sb,mode);
return k;
}
}
Client.java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.Key;
import java.util.Scanner;
import java.net.*;
public class Client {
public static void main(String[] args) {
String mode = "AES";
//客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式通过网络发送给服务器
Scanner scanner = new Scanner(System.in);
Socket mysocket;
DataInputStream in = null;
DataOutputStream out = null;
try {
mysocket = new Socket("127.0.0.1", 2010);
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
System.out.println("客户端已连接成功:");
String formula = scanner.nextLine();
String regex = ".*[^0-9|+|\\-|*|÷|(|)|\\s|/].*";
if (formula.matches(regex)) {
System.out.println("输入了非法字符");
System.exit(1);
}
String output = "";
MyBC myBC = new MyBC();
try {
//中缀转后缀
output = MyBC.getrp(formula);
} catch (Exception e) {
System.out.println(e.getMessage());
System.exit(1);
}
//使用AES进行后缀表达式的加密
KeyGenerator kg = KeyGenerator.getInstance(mode);
kg.init(128);
SecretKey k = kg.generateKey();//生成密钥
byte mkey[] = k.getEncoded();
Cipher cp = Cipher.getInstance(mode);
cp.init(Cipher.ENCRYPT_MODE, k);
byte ptext[] = output.getBytes("UTF8");
byte ctext[] = cp.doFinal(ptext);
//将加密后的后缀表达式传送给服务器
String out1 = BtoA.parseByte2HexStr(ctext);
out.writeUTF(out1);
//创建客户端DH算法公、私钥
DH.createPubAndPriKey("Clientpub.txt","Clientpri.txt");
//将客户端公钥传给服务器
FileInputStream fp = new FileInputStream("Clientpub.txt");
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();
String pop = BtoA.parseByte2HexStr(kb);
out.writeUTF(pop);
Thread.sleep(1000);
//接收服务器公钥
String push = in.readUTF();
byte np[] = AtoB.parseHexStr2Byte(push);
ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream (np));
Key k2 = (Key)ois.readObject();;
FileOutputStream f2 = new FileOutputStream("Serverpub.txt");
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(k2);
//生成共享信息,并生成AES密钥
SecretKeySpec key = Agree.createKey("Serverpub.txt", "Clientpri.txt");
//对加密后缀表达式的密钥进行加密,并传给服务器
cp.init(Cipher.ENCRYPT_MODE, key);
byte ckey[] = cp.doFinal(mkey);
String Key = BtoA.parseByte2HexStr(ckey);
out.writeUTF(Key);
//接收服务器回答
String s = in.readUTF();
System.out.println("客户收到服务器的回答:" + s);
} catch (Exception e) {
System.out.println("服务器已断开" + e);
}
}
}
DH.java
import javax.crypto.spec.DHParameterSpec;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
public class DH {
private static final byte SKIP1024_MODULUS_BYTES[] = {
(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 SKIP1024_MODULES = new BigInteger(1, SKIP1024_MODULUS_BYTES);
private static final BigInteger SKIP1024_BASE = BigInteger.valueOf(2);
public static void createPubAndPriKey(String inpub,String inpri) throws Exception{
DHParameterSpec dhp = new DHParameterSpec(SKIP1024_MODULES, SKIP1024_BASE);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
kpg.initialize(dhp);
KeyPair kp = kpg.generateKeyPair();
PublicKey pbk = kp.getPublic();
PrivateKey prk = kp.getPrivate();
FileOutputStream f1 = new FileOutputStream(inpub);
ObjectOutputStream b1 = new ObjectOutputStream(f1);
b1.writeObject(pbk);
//文件名通过命令行参数指定,第一个命令行参数对应的文件保存公钥,第二个命令行参数对应的文件保存私钥
FileOutputStream f2 = new FileOutputStream(inpri);
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(prk);
}
}
Server.java
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 Server {
public static void main(String[] args) {
String mode = "AES";
ServerSocket serverForClient = null;
Socket socketOnServer = null;
DataOutputStream out = null;
DataInputStream in = null;
try{
serverForClient = new ServerSocket(2010);
}catch (IOException e1){
System.out.println(e1);
}
String result;
try{
System.out.println("等待客户呼叫:");
socketOnServer = serverForClient.accept();
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
//接收加密后的后缀表达式
String cformula = in.readUTF();
byte cipher[] = AtoB.parseHexStr2Byte(cformula);
//接收Client端公钥
String push = in.readUTF();
byte np[] = AtoB.parseHexStr2Byte(push);
//生成服务器共、私钥
DH.createPubAndPriKey("Serverpub.txt","Serverpri.txt");
//将服务器公钥传给Client端
FileInputStream fp = new FileInputStream("Serverpub.txt");
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();
String pop = BtoA.parseByte2HexStr(kb);
out.writeUTF(pop);
Thread.sleep(1000);
//生成共享信息,并生成AES密钥
SecretKeySpec key = Agree.createKey("Serverpub.txt","Clientpri.txt");
String k = in.readUTF();//读取加密后密钥
byte[] encryptKey = AtoB.parseHexStr2Byte(k);
//对加密后密钥进行解密
Cipher cp = Cipher.getInstance(mode);
cp.init(Cipher.DECRYPT_MODE,key);
byte decryptKey [] = cp.doFinal(encryptKey);
//对密文进行解密
SecretKeySpec plainkey=new SecretKeySpec(decryptKey,mode);
cp.init(Cipher.DECRYPT_MODE, plainkey);
byte []plain=cp.doFinal(cipher);
//计算后缀表达式结果
String formula = new String(plain);
try{
Float s1 = MyDC.calrp(formula);
result = s1.toString();
//后缀表达式formula调用MyDC进行求值
}catch (Exception e){
result = e.getMessage();
}
//将计算结果传给Client端
out.writeUTF(result);
}catch (Exception e){
System.out.println("客户已断开"+e);
}
}
}
运行效果
检查点五:
结对编程:
1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文和明文的MD5値发送给服务器
- 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
- 服务器接收到后缀表达式表达式后,进行解密,解密后计算明文的MD5值,和客户端传来的MD5进行比较,一致则调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
编写代码
Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client5 {
public static void main(String args[]) throws Exception {
String key1="";
int n1=-1;
byte [] a1=new byte[128];
try{ File f=new File("key1.dat");
InputStream in = new FileInputStream(f);
while((n1=in.read(a1,0,100))!=-1) {
key1=key1+new String (a1,0,n1);
}
in.close();
}
catch(IOException e) {
System.out.println("File read Error"+e);
}
String sharekey="";
int n=-1;
byte [] a=new byte[128];
try{ File f=new File("key1.dat");
InputStream in = new FileInputStream(f);
while((n=in.read(a,0,100))!=-1) {
sharekey=sharekey+new String (a,0,n);
}
in.close();
}
catch(IOException e) {
System.out.println("File read Error"+e);
}
Socket mysocket;
DataInputStream in=null;
DataOutputStream out=null;
System.out.println("请输入算式:");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();//输入算式
str=MyBC.getrp(str);
String secret=Encoder.AESEncode(key1, str);//客户端对表达式进行加密
String md=DigestPass.MD5(str);//客户端提供的MD5
key1 = Encoder.AESEncode(sharekey,key1);//客户端对密钥进行DH加密
try{ mysocket=new Socket("127.1.0.0",2010);
in=new DataInputStream(mysocket.getInputStream());
out=new DataOutputStream(mysocket.getOutputStream());
out.writeUTF(key1);
out.writeUTF(secret);
out.writeUTF(md);
String s=in.readUTF(); //in读取信息,堵塞状态
System.out.println("客户收到服务器的回答:"+s);
Thread.sleep(50000);
}
catch(Exception e) {
System.out.println("服务器已断开"+e);
}
}
}
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String args[]) throws IOException{
String sharekey="";
int n=-1;
byte [] a=new byte[128];
try{ File f=new File("key1.dat");
InputStream in = new FileInputStream(f);
while((n=in.read(a,0,100))!=-1) {
sharekey=sharekey+new String (a,0,n);
}
in.close();
}
catch(IOException e) {
System.out.println("File read Error"+e);
}
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 keyone =in.readUTF();//读取被DH算法加密的密钥
String truekey = Encoder.AESDncode(sharekey,keyone);//使用共享密钥对被加密的原密钥解密。
String secret =in.readUTF(); // in读取信息,堵塞状态
System.out.println("服务器收到的信息:"+secret);
String mdClient=in.readUTF();
System.out.println("客户端提供的MD5为:"+ mdClient);
String clear = Encoder.AESDncode(truekey,secret);//使用原密钥解密表达式
Float answer=MyDC.calrp(clear);
if((mdClient.equals(DigestPass.MD5(clear)))==true) {//判断MD5值是否相等,若相等,则返回答案
System.out.println("MD5值匹配");
System.out.println("服务器提供的解密:" + clear);
System.out.println("服务器解出密文的MD5为:" + DigestPass.MD5(clear));
out.writeUTF(answer + "");
}
Thread.sleep(500);
}
catch(Exception e) {
System.out.println("客户已断开"+e);
}
}
}
DigestPass.java
import java.security.*;
public class DigestPass{
static String MD5(String str) throws Exception{
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(str.getBytes("UTF8"));
byte s[ ]=m.digest( );
String result="";
for (int i=0; i<s.length; i++){
result+=Integer.toHexString((0x000000ff & s[i]) |
0xffffff00).substring(6);
}
return result;
}
}
SEnc.java
import java.io.*;
import java.security.*;
import javax.crypto.*;
public class SEnc{
public static void main(String args[]) throws Exception{
String s="Hello World!";
FileInputStream f=new FileInputStream("key1.dat");
ObjectInputStream b=new ObjectInputStream(f);
Key k=(Key)b.readObject( );
Cipher cp=Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, k);
byte ptext[]=s.getBytes("UTF8");
for(int i=0;i<ptext.length;i++){
System.out.print(ptext[i]+",");
}
System.out.println("");
byte ctext[]=cp.doFinal(ptext);
for(int i=0;i<ctext.length;i++){
System.out.print(ctext[i] +",");
}
FileOutputStream f2=new FileOutputStream("SEnc.dat");
f2.write(ctext);
}
}
三、问题与解决
问题一:
解决方案:
在IDEA上JDK8以上的版本取消了sun.misc的引,但由于找不到其他可以代替BASE将字节码转换为字符串的方式,这里将JDK的版本还原到了8.0
四、感悟
本次实验是对个人编码理解能力与操作能力的考验,感觉自己在许多方面还需要加强,结对的过程中,文航给我提供了很多帮助,很是感谢。