Beijing Institute of Electronic Technology
Lab Report
Course: Mobile Platform Application development Practice class: 201592 Name: Ai Ying No.: 20159201
Score: ___________ Instructor: Lou Jia Peng Experimental Date: 2015.10.25
Experiment Name: Java Network Programming and security
Experiment content: 1, Master Socket program writing 2, mastering the use of cryptographic technology 3, design a secure transmission system
My lab partner is Shi Yuting http://www.cnblogs.com/20159205syt/, the client is in my charge and she's in charge of the server.
Experimental steps:
1. Secure transmission based on Java socket
2, give TCP to implement the client and server, pair programming one person responsible for the client one person responsible for the server
4. Choose symmetric algorithm for data encryption
5. Select asymmetric algorithm for key distribution of symmetric encryption key
6, select the MD5 algorithm for integrity verification.
In this experiment, I used DES encryption and RSA decryption.
Experimental results:
The server sets the port number and opens the service:
The client runs the encrypted data and the hash value of the plaintext, and receives a successful response from the server.
(e,n) is the server's public key pair, which is used to encrypt the session key, and C is the encrypted session key.
The server obtains C from the client to decrypt the session key, decrypts the ciphertext to the plaintext, and finally uses the hash algorithm to see if the match is successful.
D is the private key of the server, and M is the session key. The read cipher is decrypted with the session key to get 20159201 Ai Ying of plaintext. Finally, the hash value matches successfully.
Experiment Code:
Client:
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.*;p ublic Class Client {public static void main (String args[]) throws exception{try {keygenerator Kg=keygenera Tor.getinstance ("Desede"); a method for creating a symmetric key is provided in the Keygenerator class in//java; Kg.init (168); Initializes the key generator, specifying the length of the key. Secretkey K=kg.generatekey ();//Generate a key, use the first step to obtain 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. Byte[] ptext2= k.getencoded ();//Gets the primary encoding format and places the returned encoding in an array of type Byte. Socket socket = new Socket ("127.0.0.1", 2048);//create 8080 port connected to server BufferedReader in = new BufferedReader (New Input StreamReader (Socket.getinputstream ()));//Get input stream PrintWriter out=new printwriter from server side (new BufferedWriter Utstreamwriter (Socket.getoutputstream ())), true); Gain output to the server-side output data BufferedReader stdin = new BufferedReader (new InputStreamReader (system.in)); Enter information from the keyboard//The public key of the server-side RSA encrypts the key of Des FileInputStream f3=new fileinputstream ("C:/skey_rsa_pu B.dat ");//Read the saved object in the file to use ObjectInputStream b2=new ObjectInputStream (F3); Rsapublickey pub_key= (Rsapublickey) b2.readobject ();//Generate Public key BigInteger e=pub_key.getpublicexponent (); BigInteger n=pub_key.getmodulus ();//Mold System.out.println ("e=" +e); System.out.println ("n=" +n);//(N,E) is the public key BigInteger m=new BigInteger (PTEXT2); BigInteger C=m.modpow (e,n); System.out.println ("c=" +c); String cs=c.tostring (); OUT.PRINTLN (CS); Transfer to server System.out.print ("Please enter data to be sent:"); String S=stdin.readline (); Read the sent message from the keyboard Cipher cp=cipher.getinstance ("Desede");//Get Cipher instance cipher cp.init (Cipher.encrypt_mode, k);//Initialize cipher Encrypt_mode representationEncryption Decrypt_mode decryption, K is the key byte by[]=s.getbytes ("UTF8");//Gets the UTF8 byte code of the string byte miby[]=cp.dofinal (by);//encryption After the byte code string STR=PARSEBYTE2HEXSTR (Miby);//Get ciphertext string out.println (str); Transfer to the server//send the client's plaintext hash value to ciphertext String x=s; MessageDigest m2=messagedigest.getinstance ("MD5");//generates MessageDigest objects through its static method getinstance (). M2.update (X.getbytes ());//x generates a string array with the GetBytes () method for the string that needs to be computed. byte ss[]=m2.digest ();//The result of the calculation is returned by an array of byte types. String result= "";//converts the calculated result SS to a string for (int i=0; i<ss.length; i++) {result+=integer.tohexstring (0x 000000FF & Ss[i]) | 0XFFFFFF00). substring (6); } System.out.println (Result); OUT.PRINTLN (result); Str=in.readline ();//Read result System.out.println ("The result received from the server is:" +STR); } catch (Exception e) {System.out.println (e); }}//convert binary to 16 binary public staticString 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 (); }//convert 16 binary to binary 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 * + low); } return result; } }
Server-side:
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 Server {public static void main (String args[]) throws Exception {ServerSocket link = null; Socket socket = NULL; try {link = new ServerSocket (2049);//Create Server Socket SYSTEM.OUT.PRINTLN ("Port number:" + link.getlocalport ()); SYSTEM.OUT.PRINTLN ("Server has started ..."); Socket = Link.accept (); Wait for Client connection System.out.println ("Connection already established"); Get a reference to the network input stream object BufferedReader in = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); Gets a reference to the network output stream object PrintWriter out = new PrintWriter (New BufferedWriter (socket.getoutputstr EAM ())), true); Decrypt the key of DES with the private key of the server-side RSA String line = In.readline (); BigInteger cipher = new BigInteger (line); FileInputStream f = new FileInputStream ("C:/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.pr Intln ("d=" + D); System.out.println ("n=" + N); System.out.println ("m=" + M); byte[] keykb = M.tobytearray (); Decrypt ciphertext by using des String ReadLine = in.readline ();//Read data sent by client FileInputStream F2 = new FileInputStream ("C:/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");//Code Conversion SYSTEM.OUT.PRINTLN ("received from client information:" + P); Print decryption result//Use hash function to detect clear text integrity String Aline3 = In.readline (); String x = p; MessageDigest m2 = messagedigest.getinstance ("MD5");//Use MD5 algorithm to return MessageDigest object that implements the specified digest algorithm 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). s Ubstring (6); } System.out.println (Result); if (aline3.equals (Result)) {System.out.println ("match succeeded"); } out.println ("Match succeeded"); Out.close (); In.close (); Link.close (); } catch (Exception e) {System.out.println (e); }}//binary converted to 16 to prevent byte[] numbers from being converted to string type data loss public static string Parsebyte2hexstr (Byte buf[]) {Stringbu Ffer 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 ());//Convert lowercase letters in a string into uppercase letters and then add them to the string} return Sb.tostring (); }//convert 16 binary to binary public static byte[] Parsehexstr2byte (String hexstr) {if (Hexstr.length () < 1) r Eturn 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 * + low); } return result; }}
Experimental questions
1. Two computers connected to the problem, the client has connection reset error.
Server side has invalid key length error.
Debugging many times did not succeed, but will this code in the classmate computer running program implementation, which makes me very confused, I will continue to do this experiment with my lab partner, before the next week to check the teacher This problem solved
2. The port should be replaced after each communication, otherwise the experiment will fail.
Java Experiment Report (experiment five)