Java Experiment Five (network programming)

Source: Internet
Author: User

Real Inspection report

Course: Java Programming Class: 1351 Name: Kang Wenmin No.: 20135112

Score: Instructor: Lou Jia Peng Experimental Date: 2015.6.9

Experiment level: Preview degree: Experiment time: 15:20-18:00

Instrument Group: Compulsory/Elective: Experiment Number: 5

Experiment name: TCP transmission and encryption and decryption

First, the contents of the experiment

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. Use Git for version control.

5. Complete the Blog

Two. The experimental process.

Code

  Client

  

Package Chapter9;

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.*;
Import Java.security.MessageDigest;
Import javax.crypto.*;

public class Client {

public static void Main (string[] args) throws Exception {
Establish a connection to the server
InetAddress addr = Inetaddress.getbyname (null);
Socket socket = new socket (addr,server.port);
Socket socket = new Socket ("192.168.88.1", 8080);
try {
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)); Enter information from the keyboard

Get DES encryption key k
try {
keygenerator kg = keygenerator.getinstance ("Desede");
Kg.init (168);
Secretkey SK = Kg.generatekey (); Get key K
byte[] Ktext = sk.getencoded ();//Get the encoding format of the key K???
FileOutputStream f = new FileOutputStream ("Key1.dat");
ObjectOutputStream B1 = new ObjectOutputStream (f);
B1.writeobject (SK);
B1.close ();

} catch (Exception e) {
E.tostring ();
}

Send Message Redaction
System.out.println ("Please enter the message to be sent:");
String s = stdin.readline (); Read the message to be sent from the keyboard

FileInputStream f = new FileInputStream ("Key1.dat");
ObjectInputStream b2 = new ObjectInputStream (f);
Key key = (key) b2.readobject ();
B2.close ();
byte[] Ktext = key.getencoded ();//Get the encoding format of the key K???
Cipher CP = Cipher.getinstance ("Desede");
Cp.init (Cipher.encrypt_mode, key);

byte ptext[] = S.getbytes ("UTF8");
System.out.println ("");
byte ctext[] = cp.dofinal (Ptext);
SYSTEM.OUT.PRINTLN ("Ciphertext sent to the server:");
String Cipher=new string (Ctext, "UTF8");
OUT.PRINTLN (cipher);

With each other's convention encryption key K
try {
Keypairgenerator KPG = keypairgenerator.getinstance ("RSA");
Kpg.initialize (1024);
KeyPair KP = Kpg.genkeypair ();
PublicKey Pbkey = Kp.getpublic ();
Rsapublickey Pub_key = (rsapublickey) pbkey;//get the public key

BigInteger e = Pub_key.getpublicexponent ();
BigInteger n = pub_key.getmodulus ();
BigInteger m = new BigInteger (ktext); //?? How large integers are generated
BigInteger C = M.modpow (e, N);
System.out.println ("c=" + C);
String cs = c.tostring ();
OUT.PRINTLN (CS); Transfer to server

Sends the client's plaintext hash value to the other party
String x = s;
MessageDigest m2 = messagedigest.getinstance ("MD5");
M2.update (X.getbytes ());//x is the string to be evaluated

byte ss[] = M2.digest ();//The result of the calculation is returned by an array of byte types.
string result = "";//Convert the calculation result to a string

for (int i = 0; i < ss.length; i++) {
Result + = Integer.tohexstring ((0x000000ff & Ss[i]) | 0xffffff00)
. substring (6);
}
SYSTEM.OUT.PRINTLN ("Hash Value:" +result);
OUT.PRINTLN (result);

Read the server feedback results
String str = in.readline ();
SYSTEM.OUT.PRINTLN ("The result received from the server is:" + str);

} catch (Exception e) {
E.tostring ();
}
} finally {
System.out.println ("Closing ...");
Socket.close ();
}
}
}

 Server

  

Package Chapter9;

Import java.io.*;
Import Java.math.BigInteger;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import Java.security.KeyPair;
Import Java.security.KeyPairGenerator;
Import Java.security.MessageDigest;
Import Java.security.PrivateKey;
Import Java.security.PublicKey;
Import Java.security.interfaces.RSAPrivateKey;

Import Javax.crypto.Cipher;
Import Javax.crypto.spec.SecretKeySpec;

public class Server {
public static final int PORT = 8080;

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

ServerSocket s = new ServerSocket (PORT);
SYSTEM.OUT.PRINTLN ("Server startup ... : "+ s);
try {
Socket socket = s.accept ();

try {
SYSTEM.OUT.PRINTLN ("Successfully established the connection! "+ socket");
BufferedReader in = new BufferedReader (New InputStreamReader (
Socket.getinputstream ()));
PrintWriter out = new PrintWriter (New BufferedWriter (
New OutputStreamWriter (Socket.getoutputstream ())), true);
InputStream ins = Socket.getinputstream ();//Read Byte stream

SYSTEM.OUT.PRINTLN ("Receiving ciphertext from client:");
String msg = In.readline ();
byte ctext[] = Msg.getbytes ("UTF8");

Decryption of DES keys using the private key of the server-side RSA
Keypairgenerator KPG = keypairgenerator.getinstance ("RSA");
Kpg.initialize (1024);
KeyPair KP = Kpg.genkeypair ();
Privatekey Prkey = Kp.getprivate ();
FileOutputStream F2 = new FileOutputStream ("Skey_rsa_priv.dat");
ObjectOutputStream b2 = new ObjectOutputStream (F2);
B2.writeobject (Prkey);
B2.close ();

String line = In.readline ();//Gets the string that the client came from line
BigInteger cipher = new BigInteger (line);
FileInputStream f = new FileInputStream ("Skey_rsa_priv.dat");
ObjectInputStream B = new ObjectInputStream (f);
Rsaprivatekey PRK = (rsaprivatekey) b.readobject ();
B.close ();
BigInteger d = prk.getprivateexponent ();
BigInteger n = prk.getmodulus ();//mod n
BigInteger m = Cipher.modpow (d, N);//M=d (mod n)

byte[] keykb = M. Tobytearray (); Get the key K for DES, byte array type


///With Des key K decryption
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 ("Decrypted plaintext is:");
SYSTEM.OUT.PRINTLN (P);

Verify message integrity with hash
String aline = In.readline (); Get the value of the hash function coming in
String x = p;
MessageDigest m2 = messagedigest.getinstance ("MD5");//Use MD5 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). SUBSTRING (6);
}
if (aline.equals (result)) {
SYSTEM.OUT.PRINTLN ("message complete");
}
OUT.PRINTLN ("The message is incomplete!! ");
Out.close ();
In.close ();
} finally {
System.out.println ("Closing ...");
Socket.close ();
}
} finally {
S.close ();
}
}
}

Third, the experiment sentiment

 Personally, this experiment is difficult. The difficulty lies not in the understanding of RSA digital signatures in cryptography, but in how the code is used by the teacher, as well as in some details.

At first did not review the book on the IO stream knowledge, do not understand why the DES encrypted byte array into a string, later only to understand that because InputStreamReader, Outputstreamreader is the input output of the character. Later attempts to use the InputStream byte stream to operate, found that the initial size of the array needs to be more troublesome, but in the process of consolidating the knowledge of IO.

The biggest feeling in the experiment is that there are too many data types, and they always have to be converted back and forth between byte arrays, String, BigInteger, and a bit dizzy. However, it is good to understand in general what is done at each stage and what type of data to input and output. However, there are doubts:

1. How to generate BigInteger from byte arrays? Is it direct stitching?

2. What is the S_keykb.java in the given data? What is the difference between a class in two hash folders? Which do you use?

3, the Internet search data found that the public static byte[] Parsehexstr2byte (String hexstr) Such a function, why to convert between binary and 16 binary??

4, the biggest question: Why do I run with the following error? (Looks like a math error)

Exception in thread "main" Java.security.InvalidKeyException:Invalid key length:128 bytes
At Com.sun.crypto.provider.DESedeCipher.engineGetKeySize (desedecipher.java:370)
At Javax.crypto.Cipher.passCryptoPermCheck (cipher.java:1062)
At Javax.crypto.Cipher.checkCryptoPerm (cipher.java:1020)
At Javax.crypto.Cipher.implInit (cipher.java:796)
At Javax.crypto.Cipher.chooseProvider (cipher.java:859)
At Javax.crypto.Cipher.init (cipher.java:1229)
At Javax.crypto.Cipher.init (cipher.java:1166)
At Chapter9. Server.main (server.java:66)

  

Many of the above issues need to be solved, and strive to understand before the Java course, and through acceptance. Friday because of the 46-level network, failed to publish the blog in time, but also hope that teachers forgive.

  

Java Experiment Five (network programming)

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.