Java Experiment 520,135,104

Source: Internet
Author: User
Tags cos sendfile

Course: Java Programming Class: 1351 Name: Liu Shuai Study No.: 20135104

Score: Instructor: Lou Jia Peng Experimental Date: 2015.6.9

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

Instrument Group: 11 Compulsory/Elective: Experiment Number: 5

Experiment name: TCP transmission and encryption and decryption

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

5. Complete the Blog

Experimental instrument:

Name

Model

Number

Pc

Macbook Air (Win7 system)

1

Pair of partners: 20135130 Wangkuandong

I'm responsible for sending files, he's responsible for receiving files

One, the code:

Package chuanwenjian1;  Import java.io.*;  Import Java.net.ServerSocket; Import Java.net.Socket;

/**  * Send end  */  public class Client {        //int to byte    &n bsp;   public static byte[] I2B (int i) {          return new byte[]{& nbsp                 (Byte) ((I >> 24) & 0xFF),                  ( BYTE) ((I >>) & 0xFF),                   (Byte) ((I >> 8) & 0xFF),                   (Byte) (I & 0xFF)          };     }    

public static void Main (String args[]) throws ioexception{//after constructing this class with a constructor, send the File New Client (). SendFile ("localhost", 8001,   "G://java123//chuanshu//senc.dat"); New Client (). SendFile ("localhost", 8001, "G://java123//chuanshu//keykb2.dat");

}

   /**      * Send file. File size cannot be greater than {@link Integer#max_value}      *      * @param hostname receive host name or IP address &NB sp;    * @param port     Receive port number      * @param filepath file path      *      * @throws ioexception If read file or send failed      */       public void SendFile (string hostname, int port, string filepath) throws IOException {  &nbs p;       File File = new file (filepath);           FileInputStream is = new FileInputStream (filepath);              SOCKET SOCKET = new socket (hostname, port);          dataoutputstream os = New DataOutputStream (Socket.getoutputstream ());             Try {  &Nbsp;           int length = (int) file.length ();               System.out.println ("Send file:" + file.getname () + ", Length:" + Length);                // will send file name and file contents and write to file stream                writefilename ( File, OS);              writefilecontent (IS, OS, length );         } finally {               os.close ();              Is.close ();         }     }         //Output file contents        private void Writefilecontent (InputStream is, dataoutputstReam OS, int length) throws IOException {         //output file length, convert int to byte  & nbsp;      os.write (i2b (length));             //Output file contents            byte[] buffer = new byte[4096];  & nbsp;       int size;          while (size = Is.read (buffer))! =-1) {              os.write (buffer, 0, size);         }     }         //Output file name        private void writefilename (file file, DataOutputStream os) throws IO Exception {          byte[] fn_bytes = File.getname (). GetBytes ();             os.write (i2b (FN_BYTES.LEngth);        //output filename length             os.write (fn_bytes);   //output file name       } }

Package Myrsa;

Import Java.io.FileInputStream; Import Java.io.FileOutputStream; Import Java.io.InputStream; Import Java.io.ObjectInputStream; Import Java.io.ObjectOutputStream; Import Java.io.OutputStream; Import Java.security.KeyPair; Import Java.security.KeyPairGenerator; Import Java.security.SecureRandom;

Import Javax.crypto.Cipher; Import Javax.crypto.CipherInputStream; Import Javax.crypto.CipherOutputStream;

public class Myrsa {/** * Saves a pair of genetic keys to the Key.dat file */public void Saversakey () {try {securerandom sr = new SecureRandom (); keypairgenerator kg = keypairgenerator.getinstance ("RSA"); Kg.initialize (1024x768, SR); FileOutputStream fos = new FileOutputStream ("G://java123//chuanshu//key.dat"); ObjectOutputStream oos = new ObjectOutputStream (FOS); Generate Key Oos.writeobject (Kg.generatekeypair ()); Oos.close (); } catch (Exception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("Get Key pair success! "); }

/** * Reads the RSA encryption key and decryption key from the file. * * @return KeyPair return symmetric key */public static KeyPair Getkeypair () {//Generate new key pair KeyPair KP = null; try {String fileName = "G: Java123//chuanshu//key.dat "; FileInputStream is = new FileInputStream (fileName); ObjectInputStream oos = new ObjectInputStream (IS); KP = (KeyPair) oos.readobject (); Oos.close (); } catch (Exception e) {e.printstacktrace ();} return KP; KP is a key pair}

The

/** * file is encrypted and saved in the destination file destfile * * @param srcfilename *             files to encrypt such as C:/test/srcfile.txt * @param destfilename *             after encrypting file name such as c:/encrypted file. txt */public static void EncryptFile (String srcfilename, String destfilename) thr oWS Exception {Cipher Cipher = cipher.getinstance ("RSA"); Cipher.init (Cipher.encrypt_mode, Getkeypair (). Getpublic ()); Initialize the dongle with public key and cryptographic mode inputstream is = new FileInputStream (srcfilename); Read in OutputStream out from source file = new FileOutputStream (destfilename); Output CipherInputStream cis = new CipherInputStream (is,cipher) to the destination file; Pass the input stream and the encryption of the source file as parameters to the encrypted input stream byte[] buffer = new BYTE[100]; int R; while ((R=cis.read (buffer)) >=0) {//reads from the encrypted read stream Out.write (buffer,0,r); //writes the read to the output streams, i.e. writes to the destination file} cis.close (); Out.close (); Is.close (); SYSTEM.OUT.PRINTLN ("File encryption processing is over!") "); }

The

/** * file is decrypted and saved in the destination file destfile * * @param srcfilename *             encrypted files such as c:/. txt * @param destfilename *             decrypted file name such as c:/test/decrypted file. txt */public static void DecryptFile (String srcfilename, string destfilename) thro WS Exception {Cipher Cipher = cipher.getinstance ("RSA"); Cipher.init (Cipher.decrypt_mode, Getkeypair (). Getprivate ()); In the same way, this is only replaced by the decryption mode inputstream is = new FileInputStream (srcfilename); OutputStream out = new FileOutputStream (destfilename); CipherOutputStream cos = new CipherOutputStream (out,cipher); byte[] buffer = new byte[128]; int R; while ((R=is.read (buffer)) >=0) {cos.write (buffer,0,r);} cos.close (); Out.close (); Is.close (); System.out.println ("File decryption processing is over!") "); }

public static void Main (string[] args) {Myrsa fileutils=new myrsa (); Fileutils.saversakey (); Myrsa.getkeypair (); try {myrsa.encryptfile ("G://java123//chuanshu//keykb1.dat", "G://java123//chuanshu//keykb2.dat");} catch ( Exception e) {

E.printstacktrace (); }/*try {myrsa.decryptfile ("G://java123//chuanshu//keykb2.dat", "G://java123//chuanshu//keykb3.dat");} catch ( Exception e) {

E.printstacktrace (); } */ }

}

Package Hash;

Import Java.io.FileInputStream; Import java.io.FileNotFoundException; Import java.io.IOException; Import java.security.*; public class hash{     public static void Main (String args[]) throws IOException, Nosuchalgorithmexc eption {        /* original  string x=args[0];*/         //senc.dat read ciphertext from a file and coexist in the Ctext array          FileInputStream f=new FileInputStream ("G://java123//chuanshu//senc.dat");          int num=f.available ();          byte[] Ctext=new byte[num];                    F.read (ctext);          messagedigest m=messagedigest.getinstance ("MD5");//initialization of the digest           m.update (ctext);//x is the string to digest, and M is the tool that generates the digest &NBsp;        byte s[]=m.digest ()//The generated digest exists in byte array s           String result= "";          for (int i=0; i<s.length; i++) {             result+=integer.tohexstring ((0X000000FF & S[i]) |      0XFFFFFF00). SUBSTRING (6);  //Converts the decimal number in S to hexadecimal number, exists in result string      }           System.out.println (Result); Result is the generated digest string      }}

Package DES;
Import java.io.*;
Import java.security.*;
This is the encryption class for DES
Import java.security.*;
Import javax.crypto.*;
public class senc{
public static void Main (String args[]) throws exception{
String s= "If you have Susan a gift, why not Zhichitianya." July the sea once, unfamiliar familiar willing to lead. ";//string to be encrypted
FileInputStream f=new FileInputStream ("Key1.dat");
ObjectInputStream b=new ObjectInputStream (f);
Key k= (Key) B.readobject ();//Read key from Key1.dat, exists in K

Cipher cp=cipher.getinstance ("Desede");
Cp.init (Cipher.encrypt_mode, k);//Initialize encryption mode and key
Converts a string into its ASCII code, which is stored in an array, because DES encryption is an integer operation.
Byte ptext[]=s.getbytes ("UTF8");//ptext is a byte array that holds strings to be encrypted, byte is integer, takes one byte
for (int i=0;i<ptext.length;i++) {
System.out.print (ptext[i]+ ",");
}

System.out.println ("");
Byte ctext[]=cp.dofinal (ptext); Encrypted, the encrypted results are stored in the Ctext array
for (int i=0;i<ctext.length;i++) {
System.out.print (Ctext[i] + ","); Ciphertext after output encryption
}

FileOutputStream f2=new FileOutputStream ("SEnc.dat");
F2.write (Ctext); Storing ciphertext in a SEnc.dat file
}
}

Second, the problems encountered and how to solve:

1, the package in the integration of the program is often prone to redefinition and variable name occupation of the problem, at this time only need to write off the duplicate definition of the part or change the volume name, but note that later the reference section also needs to change the variable name.

2. String data cannot be converted to FileOutputStream type data after the file is sent and cannot be written to the file. Later asked the class of the great God-psfo classmate, learned that should be written in bytes, according to his suggestions to correct, the problem of the edge and solution.

Third, the experimental experience

1.PSP time

Steps

Take

Percentage

Demand analysis

1.5h

21.4%

Design

2h

28.6%

Code implementation

2h

28.6%

Test

1h

14.3%

Analysis Summary

0.5h

7.1%

2. Impressions

The experiment was done with my partner and made me feel the importance of having a tacit partner. At first, there was no clue, then after research and sorting out the idea, basically clarified the experimental plan. Later, although most of the code is out of the box, but the integration is very troublesome, it is very difficult to integrate DES encryption, RSA Encryption code in a program and to compile successfully. So I think this experiment is not a simple code, but in the completion of a project, I in which the role and glue is more like, is in the effective combination of components, and eventually form a network to encrypt the transmission of the project. At the same time I also realized that Java and C + + in the encryption of the pros and cons, although Java has a very convenient encryption class can be called, but the United States to provide us with these types of computing security cannot do, but through C + + we can further expand the key length, according to the requirements of the existing conditions to design a secure encryption algorithm.

Java Experiment 520,135,104

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.