Java Programming Experiment Five

Source: Internet
Author: User
Tags object serialization

Lesson: Java Programming Experiment class: 1353 name: Fu Yujia Yuan No.: 20135321

Score: Instructor: Lou Jia Peng Experimental Date: 2015.6.9

Experimental classification: No preview degree: Experimental time: 15:30~18:00

Instrument Group: 21 Compulsory/elective: Elective experiment number: 5

Experiment name: TCP transmission and encryption and decryption

Product Escrow Address: http://git.shiyanlou.com/20135321/shiyanlou_cs212

Experimental content:

1. Run the textbook on TCP code, pair, one-person server, one-person client;

2. The use of encryption and decryption code package, compile and run code, one person encryption, one person decryption;

3. Integrated code, one person encrypted after sending via TCP;

Note: Encryption uses AES or Des/aes or DES encryption key keys and sends, using the server's public key cryptography/Public key algorithm using RSA or dh/to verify the integrity of sending information using MD5 or SHA3;

4. Complete the blog.

Experimental instrument:

Name

Model

Number

Pc

ACER

1

Virtual machines

Laboratory Building

1

I. Experimental steps

(a) Before the experiment, I spent some time to understand the AES and DES algorithm related content, and then some of the common Java statements to a certain review, for this experiment to lay a certain foundation.

I (20135321) in this experiment is mainly responsible for the server side, my partner Fu Yunjin (20135323) is responsible for the client, his blog Park address is: Http://www.cnblogs.com/20135323fuyunjin

(ii) Review of TCP

Server-side code:

Package Chapter9;

Import java.io.*;

Import java.net.*;

public class Servertest {

public static final int port=8080;

public static void Main (string[] args) throws ioexception{

ServerSocket s=new ServerSocket (PORT);

System.out.println ("Started:" +s);

try{

Socket socket=s.accept ();

try{

System.out.println ("Connection accepted:" +socket);

BufferedReader in=new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

PrintWriter out=new PrintWriter (New BufferedWriter (OutputStreamWriter ()), true);

while (true) {

String Str=in.readline ();

if (Str.equals ("END"))

Break

System.out.println ("Echoing:" +str);

Out.println (str);

}

}finally{

System.out.println ("Closing ...");

Socket.close ();

}

}finally{

S.close ();

}

}

}

Client code:

Package Chapter9;

Import java.io.*;

Import java.net.*;

public class Clienttest {

public static void Main (string[] args) throws ioexception{

InetAddress addr=inetaddress.getbyname (NULL);

System.out.println ("addr=" +addr);

Socket socket=new socket (addr,servertest.port);

try{

System.out.println ("socket=" +socket);

BufferedReader in=new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

PrintWriter out=new PrintWriter (New BufferedWriter (OutputStreamWriter ()), true);

for (int i=0;i<10;i++) {

Out.println ("Howdy" +i);

String Str=in.readline ();

System.out.println (str);

}

Out.println ("END");

}finally{

System.out.println ("Closing ...");

Socket.close ();

}

}

}

Note: To run the server-side code before you run the client code

The results of the operation are as follows:

(iii) Pre-knowledge preparation

What is a client?

A client, or user-side, is a program that corresponds to a server and provides local services to a customer. In addition to some applications that run only locally, they are typically installed on normal clients and need to work with each other on the server side. After the development of the Internet, the more commonly used clients include web browsers such as those used by the World Wide Web, e-mail clients when e-mail is received, and client software for instant Messaging. For this kind of application, it is necessary to have the corresponding server and service program in the network to provide the corresponding service, such as database service, e-mail service, etc., so that the client and server need to establish a specific communication connection to ensure the normal operation of the application.

Principle:

The relationship between the client and the server is not necessarily based on two separate machines, and the same master-slave relationship exists in the same machine. The server that provides the service and the client receiving the service may also be on the same machine, for example, we perform the browser to browse the Web page provided by the Web page, so that the same machine can act as both server and client.

What is a server side?

Server-side is a program that passively waits for a connection in network programming, the core logic of the server-side implementation of the program and the core functions of data storage. The server-side programming steps are different from the client, and are implemented in four steps, in turn:

① Listening Port: The server side is passive waiting for the connection, so after the server is started, you do not need to initiate the connection, but only need to listen to a fixed port on the local computer. This port is the server-side open to the client port, the server-side program runs the local computer's IP address is the server-side program IP address.

② Get Connected: When the client connects to the server side, the server can get a connection that contains information about the client, such as the client IP address, and so on, and the server side and the client also exchange data through the connection. Typically in server-side programming, when you get a connection, you need to turn on a dedicated thread to handle the connection, and each connection is implemented by a separate thread.

③ exchanging data: The server side is exchanging data through the connection obtained. The server-side data exchange step is to first receive the data sent by the client, then the logical processing, and then the processing of the resulting data sent to the client. In simple terms, it is the first to receive and then send, which is different from the client's data exchange sequence. In fact, the server-side connections and client connections are the same, but the data exchange steps are different. Of course, the server-side data exchange can also be done multiple times.

④ Close connection: When the server program shuts down, it needs to shut down the server side, the port that the server listens to and the memory that consumes can be freed up by shutting down the server side, realizes the connection close.

What is TCP?

TCP (transmission Control Protocol Transmission Protocol) is a connection-oriented, reliable, byte-stream-based Transport Layer communication protocol defined by the IETF RFC 793. In the simplified computer network OSI model, it accomplishes the function specified by layer Fourth transport layer, and the User Datagram Protocol (UDP) is another important transport protocol within the same layer [1]. In the Internet Protocol family (Internet Protocol suite), the TCP layer is the middle tier located above the IP layer and below the application layer. There is often a need for reliable, pipe-like connections between the application tiers of different hosts, but the IP layer does not provide such a flow mechanism, but rather provides unreliable packet switching. [1]

The application layer sends a 8-byte data stream for inter-network transmission to the TCP layer, and then TCP partitions the data stream into a packet segment of the appropriate length (the Maximum Transmission unit ([1] MTU) of the data link layer of the network that the computer is connected to. TCP then passes the result packet to the IP layer, which transmits the packet over the network to the TCP layer of the receiving end entity [1]. TCP in order to ensure that no packet loss occurs, give each packet a sequence number, while the serial number also guarantees the delivery to the receiving end of the entity's packet received sequentially. The receiving entity then sends back a corresponding acknowledgment (ACK) to the packet that was received successfully, and if the sending entity does not receive a confirmation within a reasonable round trip delay (RTT), then the corresponding packet is assumed to be lost and will be re-transmitted. TCP uses a checksum function to verify the data for errors, and to calculate checksums when sending and receiving.

In the correctness and legality of data, TCP uses a checksum function to verify the data for errors, to compute checksums both at the time of sending and receiving, and to encrypt the data using MD5 authentication.

(iv) Specific operation

1. Running DES encryption code

Import java.io.*;

Import javax.crypto.*;

public class skey_des{

public static void Main (String args[]) 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);

}

}

Setting up and decrypting files

Import java.io.*;

Import java.security.*;

public class skey_kb{

public static void Main (String args[]) 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);

Print the contents of the key encoding

for (int i=0;i<kb.length;i++) {

System.out.print (kb[i]+ ",");

}

}

}

Run:

2. Explanation of the principle:

(1) throws Exception {}//indicates that the method may produce an exception and use throws to declare the exception,//The method produces an exception and does not have to capture

(2) For example, to use "Hello" as a key to use DES for encryption and decryption:

String keystring= "Hello";

Byte[]keydata=keystring.getbytes ();

Secretkey mydeskey=new Secretkeyspec (keyData, "DES");

(3) Get key generator

Keygenerator kg=keygenerator.getinstance ("Desede");

A method for creating a symmetric key is provided in the Keygenerator class in Java. Classes in Java generally use the new operator to create objects through the constructor, but the Keygenerator class does not, and it pre-defines a static method getinstance (), which obtains objects of type Keygenerator. This class becomes a factory class or factory.

The parameter of Method getinstance () is a string type that specifies the name of the cryptographic algorithm.

(4) Initialize key generator

Kg.init (168);

This step typically specifies the length of the key. If this step is omitted, the default key length is automatically used based on the algorithm. When specifying the length, if the first step key generator uses the "DES" algorithm, the key length must be 56 bits, if "Desede", it can be 112 or 168 bits, where 112 bits are valid; if "AES", it can be 128, 192 or 256 bits.

(5) Generate key Secretkey K=kg.generatekey ();

Use the first step to get the Keygenerator type of object in the GenerateKey () method to obtain the key. It is of type Secretkey type and can be used for later encryption and decryption.

(6) Save the key in a file by using the object serialization method

FileOutputStream f=new FileOutputStream ("Key1.dat");

ObjectOutputStream b=new ObjectOutputStream (f); B.writeobject (k);

The WriteObject method provided in the ObjectOutputStream class can serialize the object and process it in a stream manner. The file output stream is passed as a parameter to the constructor of the ObjectOutputStream class so that the created key is saved in the file Key1.dat.

(v) Code implementation

In this experiment, we took a computer for pairing test. When using a computer for this lab, only two cmd windows will be opened.

Server code (more than 20,135,321 good sources):

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 computetcpserver{

public static void Main (String srgs[]) throws Exception {

ServerSocket SC = null;//NULL delegate can use default values

Socket Socket=null;

try {

sc= new ServerSocket (2123);//Create a server socket

SYSTEM.OUT.PRINTLN ("Port number:" + sc.getlocalport ());

SYSTEM.OUT.PRINTLN ("Server has started ...");

Socket = Sc.accept (); Waiting for client connections

SYSTEM.OUT.PRINTLN ("Connection already established");

Get a reference to a network input stream object

BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

Get a reference to a network output stream object

PrintWriter out=new PrintWriter (New BufferedWriter (OutputStreamWriter ()), true);

String aline2=in.readline ();//Read data sent by the client

BigInteger c=new BigInteger (aline2);

FileInputStream f=new FileInputStream ("Skey_rsa_priv.dat");//Get input bytes from Skey_rsa_priv.dat

ObjectInputStream b=new ObjectInputStream (f);

Rsaprivatekey prk= (Rsaprivatekey) b.readobject ();//rsa private Key interface

BigInteger d=prk.getprivateexponent ();//Perform large number operations

BigInteger N=prk.getmodulus ();

BigInteger M=c.modpow (d,n);

Byte[] Keykb=m.tobytearray ();

String aline=in.readline ();//Read data sent by the client

Byte[] Ctext=parsehexstr2byte (Aline);

Key k=new Secretkeyspec (keykb, "Desede");//Use the Secretkeyspec class to construct a secretkey based on a byte array.

It is useful only for the original key that can be represented as a byte array and has no key parameters associated with it, such as DES

Cipher cp=cipher.getinstance ("Desede");//Encryption and decryption

Cp.init (Cipher.decrypt_mode, k);

byte []ptext=cp.dofinal (Ctext);

String P=new string (Ptext, "UTF8");

System.out.println ("received from the client information:" +p); Returns results to the client over a network output stream

String Aline3=in.readline ();

String x=p;

MessageDigest m2=messagedigest.getinstance ("MD5");//provides information digest algorithm functions for applications, such as MD5 algorithm

is a one-way hash function that receives data of any size and outputs a fixed-length hash value.

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 ("match success");

}

Out.println ("match success");

Out.close ();

In.close ();

Sc.close ();

} 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 ();

}

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); Converting string character type data to integer data

int low = Integer.parseint (Hexstr.substring (i*2+1, i*2+2), 16);

Result[i] = (byte) (high * + low);

}

return result;

}

}

Client code (20135323 Fu Yunjin):

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 Computetcpclient {

public static void Main (String srgs[]) throws exception{

try {

Keygenerator kg=keygenerator.getinstance ("Desede");//keygenerator class provides (symmetric) key generator functionality

The key generator is constructed using one of the GetInstance class methods of this class.

Method getinstance () parameter is a string type that specifies the name of the cryptographic algorithm

Kg.init (168); Initialize the length of the specified key

Secretkey K=kg.generatekey ();//Secret (symmetric) key. The key that implements this interface returns a string in its encoded format and returns the original key byte as the result of the Getencoded method call

Byte[] ptext2=k.getencoded ();//Set a byte array to host the original key bytes

To create a socket object that connects to a specified port on a specific server

Socket socket = new Socket ("192.168.1.115", 2123);//The IP address is the IP of the bedroom network

Get the network input stream from the server side

BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

Obtain a network output stream from the client to the server-side output data

PrintWriter out=new PrintWriter (New BufferedWriter (OutputStreamWriter ()), true);

Create a keyboard input stream so that clients can enter information from the keyboard

BufferedReader stdin = new BufferedReader (new InputStreamReader (system.in));

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); Transfer over the network to the server

System.out.print ("Please enter data to be sent:");

String S=stdin.readline (); Read the data to be sent from the keyboard

Cipher cp=cipher.getinstance ("Desede"); decoding process of//des algorithm

Cp.init (Cipher.encrypt_mode, k); decoding process of//des algorithm

Byte ptext[]=s.getbytes ("UTF8"); decoding process of//des algorithm

Byte ctext[]=cp.dofinal (ptext); decoding process of//des algorithm

String str=parsebyte2hexstr (ctext); decoding process of//des algorithm

Out.println (str); Transfer over the network to the server

String x=s;

MessageDigest m2=messagedigest.getinstance ("MD5");//messagedigest class provides information digest algorithms for applications such as MD5 algorithms

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);////returns a string representation of an integer parameter as a 16-based (radix 16) unsigned integer.

}

SYSTEM.OUT.PRINTLN (result);

OUT.PRINTLN (result);

Str=in.readline ();//Read results from the network input stream

SYSTEM.OUT.PRINTLN ("The result received from the server is:" +STR); Results returned by the output server

}

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); The returned string represents an unsigned integer parameter represented by a value of 16 (radix 16)

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); Converting string character type data to integer data

int low = Integer.parseint (Hexstr.substring (i*2+1, i*2+2), 16); Converting string character type data to integer data

Result[i] = (byte) (high * + low);

}

return result;

}

}

(vi) Integration

1. Dormitory Network IP Address:

Integration operations:

(vii) PSP time

Steps

Take

Percentage

Demand analysis

50min

16.1%

Design

60min

19.3%

Code implementation

120mn

38.7%

Test

20min

6.5%

Analysis Summary

60min

19.3%

(eight) problems encountered

1. At the outset, there was no thought of establishing an inter-LAN network between the two laptop to enable the interconnection of the server and the client.

Solution: Use the computer to release WiFi or mobile phone out of hot spots or use the bedroom router for local transmission.

2. In a single laptop on the simulation experiment, initially did not think of the use of two cmd windows to operate, a single eclipse can not achieve the server side and client contact.

Solution: Through the Fu Yunjin reminds of the use of two CMD window, the successful implementation of the analog interconnect.

(ix) Experimental experience and impressions

This is the fourth Java experiment, and the last Java experiment of the semester. Compared to the first three experiments, the experiment is more focused on the integration and collocation of code, and to a certain extent, the understanding of our knowledge of cryptography. The same is a pair of programming experiments, pilots and pilots are very important, the two can also be interchangeable roles, which I have a deep understanding, because at first I think I can do a lot of code work, to the later is Fu Yunjin students grasp the focus of the experiment. In any case, we are reaping a lot of experiments and the combination code is a skill that Java programmers should have, so I feel fortunate.

Java Programming Experiment Five

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.