任务一
一、实验要求
两人一组结对编程:
0. 参考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA
- 结对实现中缀表达式转后缀表达式的功能 MyBC.java
- 结对实现从上面功能中获取的表达式中实现后缀表达式求值的功能,调用MyDC.java
- 上传测试代码运行结果截图和码云链接
二、实验原理
0.据表达式Exp = S1 + OP + S2
(S1 ,S2是两个操作数,OP为运算符)有三种标识方法:
OP + S1 + S2
为前缀表示法
S1 + OP + S2
为中缀表示法
S1 + S2 + OP
为后缀表示法
1.中缀表达式转化成后缀表达式的过程:
设立一个栈,存放运算符,首先栈为空;
从左到右扫描中缀式,若遇到操作数,直接输出,并输出一个空格作为两个操作数的分隔符;
若遇到运算符,则与栈顶比较,比栈顶级别高则进栈,否则退出栈顶元素并输出,然后输出一个空格作分隔符;
若遇到左括号,进栈;若遇到右括号,则一直退栈输出,直到退到左括号止。
当栈变成空时,输出的结果即为后缀表达式。
2.后缀表达式求值的步骤:
设置一个操作数栈,开始栈为空;
从左到右扫描后缀表达式,遇操作数,进栈;
若遇运算符,则从栈中退出两个元素,先退出的放到运算符的右边,后退出的放到运算符左边,运算后的结果再进栈,直到后缀表达式扫描完毕。
此时,栈中仅有一个元素,即为运算的结果。
三、实验代码
1.后缀转中缀
import java.util.Stack;
import java.util.StringTokenizer;
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);
}*/
}
2.求后缀表达式
import java.util.StringTokenizer;
import java.util.Stack;
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 = '/';
// 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))
{
//从栈中弹出操作数
//op2 =Integer.parseInt(stack.pop());
op2 =stack.pop();
//从栈中弹出操作数
//op1 =Integer.parseInt(stack.pop());
op1 =stack.pop();
//根据运算符和两个操作数调用evalSingleOp计算result;
result = evalSingleOp(token.charAt(0),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 (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;
}
}
3.测试代码
import java.util.Scanner;
public class MyBCTest {
public static void main (String[] args) {
String expression1=null,expression2=null, again=null;
int result,i=0,length=0;
try
{
Scanner in = new Scanner(System.in);
do
{
MyDC evaluator = new MyDC();
MyBC turner = new MyBC();
System.out.println ("Enter a valid midfix expression: ");
expression1 = in.nextLine();
//System.out.println(expression1);
expression2 = turner.turn(expression1);
while(expression2.charAt(i)!=' '){
length++;
i++;
}
//length 表示字符串包括‘ ’的字符个数
expression2 = expression2.substring(1,length-1);
//System.out.println(expression2);
result = evaluator.evaluate (expression2);
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 e)
{
e.printStackTrace();
}
}
}
四、实验截图
任务二
一、实验要求
结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式通过网络发送给服务器
- 服务器接收到后缀表达式,调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
二、实验代码
1.服务器端(本人负责编写)
import java.io.DataInputStream;
import java.io.DataOutputStream;
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("服务器启动...
");
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("计算结果: ");
// 发送键盘输入的一行
//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());
}
}
}
}
}
}
2.客服端(搭档20175216负责编写)
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" 的时候, 客户端将终止
");
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("请输入: ");
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)!=' '){
length++;
i++;
}
String str2 = str1.substring(1,length-1);
out.writeUTF(str2);
String ret = input.readUTF();
System.out.println("服务器端返回过来的是: " + ret);
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());
}
}
}
}
}
}
三、实验截图
任务三
一、实验要求
加密结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密后通过网络把密文发送给服务器
- 服务器接收到后缀表达式表达式后,进行解密(和客户端协商密钥,可以用数组保存),然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
二、实验代码
1.Server2
import java.io.DataInputStream;
import java.io.DataOutputStream;
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("服务器启动...
");
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("计算结果: ");
// 发送键盘输入的一行
//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());
}
}
}
}
}
}
2.Client2.java
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" 的时候, 客户端将终止
");
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("请输入: ");
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)!=' '){
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());
}
}
}
}
}
}
3.Skey_DES.java
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class Skey_DES{
public static void key_DES()
throws Exception{
KeyGenerator kg=KeyGenerator.getInstance("DESede");
kg.init(168);
SecretKey k=kg.generateKey( );
FileOutputStream f=new FileOutputStream("key1.dat");
ObjectOutputStream b=new ObjectOutputStream(f);
b.writeObject(k);
}
}
4.Skey_RSA.java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Skey_RSA{
public static void main(String args[]) throws Exception{
KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp=kpg.genKeyPair();
PublicKey pbkey=kp.getPublic();
PrivateKey prkey=kp.getPrivate();
// 保存公钥
FileOutputStream f1=new FileOutputStream("Skey_RSA_pub.dat");
ObjectOutputStream b1=new ObjectOutputStream(f1);
b1.writeObject(pbkey);
// 保存私钥
FileOutputStream f2=new FileOutputStream("Skey_RSA_priv.dat");
ObjectOutputStream b2=new ObjectOutputStream(f2);
b2.writeObject(prkey);
}
}
5.Skey_kb.java
import java.io.*;
import java.security.*;
/**
* Created by lxkj on 2017/6/2.
*/
public class Skey_kb{
public static void key() throws Exception{
FileInputStream f=new FileInputStream("key1.dat");
ObjectInputStream b=new ObjectInputStream(f);
Key k=(Key)b.readObject( );
byte[ ] kb=k.getEncoded( );
FileOutputStream f2=new FileOutputStream("keykb1.dat");
f2.write(kb);
// 打印密钥编码中的内容
System.out.println("密钥为:");
for(int i=0;i<kb.length;i++){
System.out.print(kb[i]+",");
}
System.out.println();
}
}
三、实验截图
任务四
一、实验要求
密钥分发结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文发送给服务器
- 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
- 服务器接收到后缀表达式表达式后,进行解密,然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
二、实验代码
1.Key_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 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);
}
}
2.KeyAgree.java
import javax.crypto.KeyAgreement;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
public class KeyAgree{
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");
}
}
3.Client4.java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.*;
import java.util.Scanner;
import java.net.*;
public class Client4 {
public static void main(String[] args) {
Socket mysocket;
DataInputStream in=null;
DataOutputStream out=null;
Scanner scanner = new Scanner(System.in);
try {
System.out.print("输入服务器的IP:");
String IP = scanner.nextLine();
InetAddress address=InetAddress.getByName(IP);
mysocket = new Socket(address, 2010);
in = new DataInputStream(mysocket.getInputStream());
out = new DataOutputStream(mysocket.getOutputStream());
Key_DH.DH("Lpub.dat","Lpri.dat");
FileInputStream my = new FileInputStream("Lpub.dat");
ObjectInputStream mypub = new ObjectInputStream(my);
Key kp = (Key) mypub.readObject();
ByteArrayOutputStream DH = new ByteArrayOutputStream();
ObjectOutputStream myDH = new ObjectOutputStream(DH);
myDH.writeObject(kp);
byte []pub = DH.toByteArray();
out.writeUTF(pub.length+"");
for(int i=0;i<pub.length;i++) {
out.writeUTF(pub[i]+ "");
}
Thread.sleep(1000);
int length = Integer.parseInt(in.readUTF());
byte cpub[] = new byte[length];
for(int i=0;i<length;i++) {
String temp = in.readUTF();
cpub[i] = Byte.parseByte(temp);
}
ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
ObjectInputStream ckey = new ObjectInputStream(ckey1);
Key k = (Key) ckey.readObject();
FileOutputStream f2 = new FileOutputStream("W1pub.dat");
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(k);
KeyAgree.Agree("W1pub.dat","Lpri.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("
请输入中缀表达式:");
while(scanner.hasNext()) {
String question = scanner.next();
MyBC change = new MyBC();
change.ChangeString(question);
String question1 = change.ChangeOrder();
System.out.println("后缀表达式为:" + question1);
SecretKeySpec k1 = new SecretKeySpec(keysb, "DESede");
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, k1);
byte ptext[] = question1.getBytes("UTF8");
byte ctext[] = cp.doFinal(ptext);
System.out.println("加密后的后缀表达式为:");
for (int i = 0; i < ctext.length; i++) {
System.out.print(ctext[i] + " ");
}
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);
Thread.sleep(500);
System.out.println("请输入中缀表达式:");
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
5.Server4.java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.*;
public class Server4 {
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 e) {
System.out.println(e);
}
System.out.println("等待客户呼叫");
try {
socketOnServer = serverForClient.accept();
out = new DataOutputStream(socketOnServer.getOutputStream());
in = new DataInputStream(socketOnServer.getInputStream());
Key_DH.DH("Wpub.dat","Wpri.dat");
int length = Integer.parseInt(in.readUTF());
byte cpub[] = new byte[length];
for(int i=0;i<length;i++) {
String temp = in.readUTF();
cpub[i] = Byte.parseByte(temp);
}
ByteArrayInputStream ckey1 = new ByteArrayInputStream(cpub);
ObjectInputStream ckey = new ObjectInputStream(ckey1);
Key k1 = (Key) ckey.readObject();
FileOutputStream f2 = new FileOutputStream("Lpub.dat");
ObjectOutputStream b2 = new ObjectOutputStream(f2);
b2.writeObject(k1);
FileInputStream my = new FileInputStream("Wpub.dat");
ObjectInputStream mypub = new ObjectInputStream(my);
Key kp = (Key) mypub.readObject();
ByteArrayOutputStream DH = new ByteArrayOutputStream();
ObjectOutputStream myDH = new ObjectOutputStream(DH);
myDH.writeObject(kp);
byte []pub = DH.toByteArray();
out.writeUTF(pub.length+"");
for(int i=0;i<pub.length;i++) {
out.writeUTF(pub[i]+ "");
}
KeyAgree.Agree("Lpub.dat","Wpri.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]+" ");
}
while(true) {
SecretKeySpec k = new SecretKeySpec(keysb, "DESede");
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE, k);
String clength = in.readUTF();
byte ctext[] = new byte[Integer.parseInt(clength)];
for (int i = 0; i < Integer.parseInt(clength); i++) {
String temp = in.readUTF();
ctext[i] = Byte.parseByte(temp);
}
byte[] ptext = cp.doFinal(ctext);
String question = new String(ptext, "UTF8");
System.out.print("
解密后的后缀表达式为:" + question);
MyDC getanswer = new MyDC();
getanswer.set(question);
Rational answer = getanswer.get();
int a = answer.getNumerator();
int b = answer.getDenominator();
float result = (float) a / b;
System.out.println("
计算出的结果为"+String.format("%.2f",result));
out.writeUTF(String.format("%.2f",result));
Thread.sleep(500);
}
}
catch(Exception e) {
System.out.println("客户已断开" + e);
}
}
}
三、实验截图
任务五
一、实验要求
完整性校验结对编程:1人负责客户端,一人负责服务器
0. 注意责任归宿,要会通过测试证明自己没有问题
- 基于Java Socket实现客户端/服务器功能,传输方式用TCP
- 客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密通过网络把密文和明文的MD5値发送给服务器
- 客户端和服务器用DH算法进行3DES或AES算法的密钥交换
- 服务器接收到后缀表达式表达式后,进行解密,解密后计算明文的MD5值,和客户端传来的MD5进行比较,一致则调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端
- 客户端显示服务器发送过来的结果
- 上传测试结果截图和码云链接
二、实验代码
1.Server.java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Key;
import java.security.MessageDigest;
import java.security.interfaces.RSAPrivateKey;
public class Server {
public static void main(String args[]) throws Exception {
ServerSocket link = null;
Socket socket = null;
try {
link = new ServerSocket(10000);// 创建服务器套接字
//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("MD5:"+result);
if (aline3.equals(result)) {
System.out.println("匹配成功");
}
exp5.MyDC evaluator = new exp5.MyDC();
int _result = evaluator.value(p);
out.println(_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;
}
}
2.Client.java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import java.math.BigInteger;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.interfaces.RSAPublicKey;
public class Client {
public static void main(String srgs[]) throws Exception {
try {
KeyGenerator kg = KeyGenerator.getInstance("DESede");
kg.init(168);
SecretKey k = kg.generateKey();
byte[] ptext2 = k.getEncoded();
Socket socket = new Socket("127.0.0.1", 10000);
System.out.println("客户端成功启动,等待客户端呼叫");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
//RSA算法,使用服务器端的公钥对DES的密钥进行加密
FileInputStream f3 = new FileInputStream("Skey_RSA_pub.dat");
ObjectInputStream b2 = new ObjectInputStream(f3);
RSAPublicKey pbk = (RSAPublicKey) b2.readObject();
BigInteger e = pbk.getPublicExponent();
BigInteger n = pbk.getModulus();
BigInteger m = new BigInteger(ptext2);
BigInteger c = m.modPow(e, n);
String cs = c.toString();
out.println(cs); // 通过网络将加密后的秘钥传送到服务器
System.out.println("请输入中缀表达式:");
//用DES加密明文得到密文
String s = stdin.readLine(); // 从键盘读入待发送的数据
String postfix = MyBC.toPostfix(s);
Cipher cp = Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, k);
byte ptext[] = postfix.getBytes("UTF8");
byte ctext[] = cp.doFinal(ptext);
String str = parseByte2HexStr(ctext);
out.println(str); // 通过网络将密文传送到服务器
// 将客户端明文的Hash值传送给服务器
String x = postfix;
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);
out.println(result);//通过网络将明文的Hash函数值传送到服务器
str = in.readLine();// 从网络输入流读取结果
System.out.println("从服务器接收到的结果为:" + str); // 输出服务器返回的结果
} catch (Exception e) {
System.out.println(e);//输出异常
} finally {
}
}
//将十六进制转换成二进制
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();
}
}
3.Skey_RSA.java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Skey_RSA{
public static void main(String args[]) throws Exception{
KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp=kpg.genKeyPair();
PublicKey pbkey=kp.getPublic();
PrivateKey prkey=kp.getPrivate();
// 保存公钥
FileOutputStream f1=new FileOutputStream("Skey_RSA_pub.dat");
ObjectOutputStream b1=new ObjectOutputStream(f1);
b1.writeObject(pbkey);
// 保存私钥
FileOutputStream f2=new FileOutputStream("Skey_RSA_priv.dat");
ObjectOutputStream b2=new ObjectOutputStream(f2);
b2.writeObject(prkey);
}
}
4.SDec.java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
public class SDec{
public static void main(String args[]) throws Exception{
// 获取密文
FileInputStream f=new FileInputStream("SEnc.dat");
int num=f.available();
byte[ ] ctext=new byte[num];
f.read(ctext);
// 获取密钥
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);
// 显示明文
String p=new String(ptext,"UTF8");
System.out.println(p);
}
}
三、实验截图
实验过程中遇到的问题
1.代码编写完成后,运行时出现双方已断开连接的提示
解决:应该是因为不同任务的服务器之间存在影响。关闭IDEA,新建了一个项目进行实验四的任务执行,问题得到解决。
实验总结与体会
这次实验一开始看实验的任务要求,有感觉很有难度。于是我主动与Java基础比我好的张雪原同学结对。在实验中我们遇到了很多问题,但在互帮互助之下,耗时四天,还是一起完成了实验。很喜欢娄老师的组队学习方式,受益匪浅!
码云链接
https://gitee.com/GeXuYang/1059724060/tree/master/20175202/exp5