当前位置: 首页 > article >正文

Java实现网络安全编程数字信封 网络安全 java

任务一

  • 题目:①编写MyBC.java实现中缀表达式转后缀表达式的功能;②编写MyDC.java实现从上面功能中获取的表达式中实现后缀表达式求值的功能
  • 中缀转后缀的算法可描述为:
  • 设置一个运算符栈,设置一个后缀表达式字符串;
  • 从左到右依次对中缀表达式中的每个字符ch分别进行以下处理,直至表达式结束:
  1. 若ch是左括号‘(’,将其入栈;
  2. 若ch是数字,将其后连续若干数字添加到后缀表达式字符串之后,并添加空格作为分隔符;
  3. 若ch是运算符,先将栈顶若干优先级高于ch的运算符出栈,添加到后缀表达式字符串之后,再将ch入栈。当‘(’运算符在栈中时,它的优先级最低。
  4. 若ch是‘)’,则若干运算符全部出栈,直到出栈的是左括号,一对括号匹配。
  • 若表达式结束,将栈中运算符全部出栈,添加到后缀表达式字符串之后。
  • 后缀表达式求值的算法可描述为(参考:娄老师的博客):
  • 设置一个操作数栈,从左向右依次对后缀表达式字符串中的每个字符ch进行处理;
  • 若ch是数字,先将其后连续若干数字转化为整数,再将该整数入栈;
  • 若ch是运算符,出栈两个值进行运算,运算结果再入栈;
  • 重复以上步骤,直至后缀表达式结束,栈中最后一个数字就是所求表达式的值。
  • 在我之前的实验一中有更为详细的代码与解释:《20165310_JavaExp1_Java开发环境的熟悉》
  • 添加的测试代码:
public class NewMyDCTester {
    public static void main(String [] args) {
        String expression;
        int result;
        try
        {
            Scanner in = new Scanner(System.in);
            NewMyDC evaluator = new NewMyDC();
            System.out.println ("Enter a valid postfix 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");
        }
    }
}
public class NewMyDCTester {
    public static void main(String [] args) {
        String expression;
        int result;
        try
        {
            Scanner in = new Scanner(System.in);
            NewMyDC evaluator = new NewMyDC();
            System.out.println ("Enter a valid postfix 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");
        }
    }
}
  • 1.
  • 实验运行结果:

任务二

  • 题目:①结对编程:一人负责客户端,另一人负责服务器;②注意责任归宿,要会通过测试证明自己没有问题;③基于Java Socket实现客户端/服务器功能,传输方式用TCP;④客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式通过网络发送给服务器;⑤服务器接收到后缀表达式,调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端;⑥客户端显示服务器发送过来的结果
  • 我的任务是客户端,代码如下:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        String str;
        System.out.println("请输入要计算的中缀式:");
        Scanner scanner=new Scanner(System.in);
        str=scanner.nextLine();
        Socket myClientSocket;
        DataInputStream in=null;
        DataOutputStream out=null;
        ChangeExpress chedExp=new ChangeExpress();
        chedExp.setOriginalExpression(str);
        chedExp.changedWay();
        System.out.println("发送给服务器的后缀式为:"+chedExp.changedExpression);
        try {
            myClientSocket = new Socket("10.1.1.165",2010);
            System.out.println("客户端已启动");
            in=new DataInputStream(myClientSocket.getInputStream());
            out=new DataOutputStream(myClientSocket.getOutputStream());
            out.writeUTF(chedExp.changedExpression);
            String answer=in.readUTF();
            System.out.println("服务器端计算结果是:"+answer);
            Thread.sleep(500);
        }
        catch (Exception e){
            System.out.println("服务器已断开"+e);
        }
    }
}

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        String str;
        System.out.println("请输入要计算的中缀式:");
        Scanner scanner=new Scanner(System.in);
        str=scanner.nextLine();
        Socket myClientSocket;
        DataInputStream in=null;
        DataOutputStream out=null;
        ChangeExpress chedExp=new ChangeExpress();
        chedExp.setOriginalExpression(str);
        chedExp.changedWay();
        System.out.println("发送给服务器的后缀式为:"+chedExp.changedExpression);
        try {
            myClientSocket = new Socket("10.1.1.165",2010);
            System.out.println("客户端已启动");
            in=new DataInputStream(myClientSocket.getInputStream());
            out=new DataOutputStream(myClientSocket.getOutputStream());
            out.writeUTF(chedExp.changedExpression);
            String answer=in.readUTF();
            System.out.println("服务器端计算结果是:"+answer);
            Thread.sleep(500);
        }
        catch (Exception e){
            System.out.println("服务器已断开"+e);
        }
    }
}
  • java.net.Socket
  • 套接字是一个网络连接的端点。在java中,使用java.net.Socket对象来表示一个套接字。要创建一个套接字,可以使用Socket的构造方法,如:public Socket(java.lang.String host, int port)。其中,host是远程机器名或IP地址,port是远程应用程序的端口号。上述代码中,IP地址为:"10.1.1.165",端口号为:2010。
  • 成功创建Socket类的一个实例后,就可以使用它发送或接收字节流。发送字节流,必须先调用Socket类的getOutputStream方法来获取一个java.io.OutputStream对象。接收字节流,可以调用Socket类的getInputStream方法,它返回一个java.io.InputStream。
  • 运行结果

任务三

  • 题目:①客户端让用户输入中缀表达式,然后把中缀表达式调用MyBC.java的功能转化为后缀表达式,把后缀表达式用3DES或AES算法加密后通过网络把密文发送给服务器;②服务器接收到后缀表达式表达式后,进行解密(和客户端协商密钥,可以用数组保存),然后调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端。其他要求同任务二。
  • 客户端RSA加密代码
import java.net.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;

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[] ptext = k.getEncoded();
            Socket socket = new Socket("192.168.43.109", 2010);
            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(ptext);
            BigInteger c = m.modPow(e, n);
            String cs = c.toString();
            out.println(cs); // 通过网络将加密后的秘钥传送到服务器
            System.out.println("请输入中缀式:");
            //用DES加密明文得到密文
            String s = stdin.readLine(); // 从键盘读入待发送的数据
            String plain = MyBC.changeWay(s);
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext1[] = plain.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext1);
            String str = parseByte2HexStr(ctext);
            out.println(str); // 通过网络将密文传送到服务器
            System.out.println("从服务器接收到的结果为:" + str); // 输出结果
        } catch (Exception e) {
            System.out.println("服务器断开连接"+e);//输出异常
        }

    }

}
import java.net.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;

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[] ptext = k.getEncoded();
            Socket socket = new Socket("192.168.43.109", 2010);
            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(ptext);
            BigInteger c = m.modPow(e, n);
            String cs = c.toString();
            out.println(cs); // 通过网络将加密后的秘钥传送到服务器
            System.out.println("请输入中缀式:");
            //用DES加密明文得到密文
            String s = stdin.readLine(); // 从键盘读入待发送的数据
            String plain = MyBC.changeWay(s);
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext1[] = plain.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext1);
            String str = parseByte2HexStr(ctext);
            out.println(str); // 通过网络将密文传送到服务器
            System.out.println("从服务器接收到的结果为:" + str); // 输出结果
        } catch (Exception e) {
            System.out.println("服务器断开连接"+e);//输出异常
        }

    }

}
  • 实验结果

任务四

  • 题目:任务三基础上增加客户端和服务器用DH算法进行3DES或AES算法的密钥交换。
  • 创建DH公钥和私钥:
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{
       //三个静态变量的定义从
// C:\j2sdk-1_4_0-doc\docs\guide\security\jce\JCERefGuide.html
// 拷贝而来
// The 1024 bit Diffie-Hellman modulus values used by SKIP
    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);
   }      
}  
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{
       //三个静态变量的定义从
// C:\j2sdk-1_4_0-doc\docs\guide\security\jce\JCERefGuide.html
// 拷贝而来
// The 1024 bit Diffie-Hellman modulus values used by SKIP
    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);
   }      
}
  • 创建共享密钥

DH算法中,A可以用自己的密钥和B的公钥按照一定方法生成一个密钥,B也可以用自己的密钥和A的公钥按照一定方法生成一个密钥,由于一些数学规律,这两个密钥完全相同。这样,A和B间就有了一个共同的密钥可以用于各种加密。本实例介绍Java中在上一小节的基础上如何利用DH公钥和私钥各自创建共享密钥。

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 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");
  }
}  
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 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");
  }
}
  • 运行结果

任务五

  • 题目:任务四的基础上,在服务器接收到后缀表达式表达式后,进行解密,解密后计算明文的MD5值,和客户端传来的MD5进行比较,一致则调用MyDC.java的功能计算后缀表达式的值,把结果发送给客户端。
  • MD5算法
    使用Java计算指定字符串的消息摘要。
    java.security包中的MessageDigest类提供了计算消息摘要的方法,
    最后的实现代码:
import java.net.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;

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[] ptext = k.getEncoded();
            Socket socket = new Socket("192.168.43.109", 2010);
            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(ptext);
            BigInteger c = m.modPow(e, n);
            String cs = c.toString();
            out.println(cs); // 传送秘钥到服务器
            System.out.println("请输入中缀式:");
            //用DES加密明文得到密文
            String s = stdin.readLine(); // 从键盘读入待发送的数据
            String plain = MyBC.changeWay(s);
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext1[] = plain.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext1);
            String str = parseByte2HexStr(ctext);
            out.println(str); // 传送密文传送到服务器
            String str = plain;
            MessageDigest m2 = MessageDigest.getInstance("MD5");
            m2.update(str.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);
            out.println(result);//传送HASH到服务器
            str = in.readLine();// 网络输入流读取结果
            System.out.println("从服务器接收到的结果为:" + str); // 输出服务器返回的结果
        } catch (Exception e) {
            System.out.println("服务器断开连接"+e);
        }

    }

    //将十六进制转换成二进制
    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();
    }
}
import java.net.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;

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[] ptext = k.getEncoded();
            Socket socket = new Socket("192.168.43.109", 2010);
            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(ptext);
            BigInteger c = m.modPow(e, n);
            String cs = c.toString();
            out.println(cs); // 传送秘钥到服务器
            System.out.println("请输入中缀式:");
            //用DES加密明文得到密文
            String s = stdin.readLine(); // 从键盘读入待发送的数据
            String plain = MyBC.changeWay(s);
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext1[] = plain.getBytes("UTF8");
            byte ctext[] = cp.doFinal(ptext1);
            String str = parseByte2HexStr(ctext);
            out.println(str); // 传送密文传送到服务器
            String str = plain;
            MessageDigest m2 = MessageDigest.getInstance("MD5");
            m2.update(str.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);
            out.println(result);//传送HASH到服务器
            str = in.readLine();// 网络输入流读取结果
            System.out.println("从服务器接收到的结果为:" + str); // 输出服务器返回的结果
        } catch (Exception e) {
            System.out.println("服务器断开连接"+e);
        }

    }

    //将十六进制转换成二进制
    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();
    }
}

    问题总结

    • 在端口和IP正确的情况下客户端与服务器无法连接:
    • 是由于没有处于同一网络中,必须在同一网络中可以连接。
    • 服务器接受不到客户端发送的消息
    • 由于阻塞问题,可用Thread类解决,或者可以改变输入输出流,在任务二中,我直接修改引用了书上例子三的代码就可以完成,但是在任务三中由于阻塞的原因无法进行通信,参考狄维佳学姐的博客,将DataOutputStream更改为PrintWriter,将DataInputStream更改为BufferReader,解决了阻塞问题。

    http://www.kler.cn/a/536302.html

    相关文章:

  • 4.PPT:日月潭景点介绍【18】
  • C++版本DES加密/解密
  • 【大数据技术】搭建完全分布式高可用大数据集群(Scala+Spark)
  • Llama最新开源大模型Llama3.1
  • 如何利用Python爬虫获取商品销量详情:应对eBay反爬策略的实战指南与代码示例
  • 结合深度学习、自然语言处理(NLP)与多准则决策的三阶段技术框架,旨在实现从消费者情感分析到个性化决策
  • 深入解析:如何利用 Python 爬虫获取商品 SKU 详细信息
  • 深入理解 YUV Planar 和色度二次采样 —— 视频处理的核心技术
  • 第30节课:前端架构与设计模式—构建高效可维护的Web应用
  • 《金字塔原理》笔记
  • 【JS】element-ui 中 table的select事件
  • source 与 shell 之详解(Detailed Explanation of Source and Shell)
  • 集合类不安全问题
  • tqdm用法教程
  • 【JavaScript】《JavaScript高级程序设计 (第4版) 》笔记-Chapter5-基本引用类型
  • Python调取本地MongoDB招投标数据库,并结合Ollama部署的DeepSeek-R1-8B模型来制作招投标垂直领域模型
  • Git(分布式版本控制系统)系统学习笔记【并利用腾讯云的CODING和Windows上的Git工具来实操】
  • 7.list
  • Kotlin协程详解——协程取消与超时
  • 博主卖DeepSeek相关课程1天收入50000元
  • 鸿蒙北向开发OpenHarmony4.1 DevEco Studio开发工具安装与配置
  • python学习过程中,Scrapy爬虫和requests库哪个更适合新手?
  • 在 MySQL 8 中配置主从同步(主从复制)是一个常见的需求,用于实现数据的冗余备份、读写分离等。
  • 前端知识速记--JS篇:柯里化
  • shell脚本的一些学习笔记----(一)
  • python编程-类结构,lambda语法,原始字符串