E. Zahra
E. Zahra

Reputation: 165

encryption and decryption using socket server and des algorithm

creating a server-client java App for encryption and Decryption using DES algorithm and a file to save my key in it ,socket for client server comunication i have problem in the decrypt function

this is my server code

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import javax.crypto.*;
import java.security.*;
import java.util.Arrays;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author ASUS
 */


 public class Server {
    
        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
            try (ServerSocket listener = new ServerSocket(3001)) {
                System.out.println("The date server is running...");
                while (true) {
    
                    try (Socket socket = listener.accept()) {
                        Key k = Client.getkey("D://key.txt");
    
                        DataInputStream in = new DataInputStream(socket.getInputStream());
                        String x = in.readUTF();
    
                        System.out.println(k);
                        System.out.println(x);
                        System.out.println(Decrypt(x, k));
    
                    }

            }
        }

    }

 

   public static String Decrypt(String cipherText, Key k) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, k);
      
   return new String (cipher.doFinal(Base64.getDecoder().decode(cipherText)),"UTF-8");
    }

    public static void gen_key() throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance("DES");
        Key k = kg.generateKey();
        String encodedKey = Base64.getEncoder().encodeToString(k.getEncoded());
        try {
            FileWriter myWriter = new FileWriter("D://key.txt");
            myWriter.write(encodedKey);

            myWriter.close();
            System.out.println("Successfully wrote  key to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }

    public static Key getkey(String filename) throws FileNotFoundException, IOException {
        InputStream is = new FileInputStream(filename);
        BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
        String line = buffer.readLine();
        StringBuilder sb = new StringBuilder();
        while (line != null) {
            sb.append(line);
            line = buffer.readLine();
        }
        String fileAsString = sb.toString();
        byte[] decodedkey = Base64.getDecoder().decode(fileAsString);
        SecretKey originkey = new SecretKeySpec(decodedkey, 0, decodedkey.length, "DES");
        return originkey;
    }
}

and this is client code

import java.io.BufferedReader;
import java.io.File;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
import java.net.Socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.crypto.*;
import  java.security.*;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.spec.SecretKeySpec;
/**
 *
 * @author ASUS
 */



  public class Client {
    
        
         public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
          gen_key();
         byte[] r;     
    Key k=getkey("D://key.txt");
         r = encrypt("fatimaalzahrasha",k);
       
               Socket socket = new Socket("127.0.0.1", 3001);
            DataOutputStream os=new  DataOutputStream(socket.getOutputStream());
            os.writeUTF(r.toString());
         }
    
         public static Key getkey(String filename) throws FileNotFoundException, IOException{
             InputStream is=new FileInputStream(filename);
             BufferedReader buffer=new BufferedReader(new InputStreamReader(is));
      String line=buffer.readLine();
      StringBuilder sb=new StringBuilder();
    while(line!=null)
    {sb.append(line);
    line=buffer.readLine();}
    String fileAsString=sb.toString();
    byte[] decodedkey=Base64.getDecoder().decode(fileAsString);
    SecretKey originkey=new SecretKeySpec(decodedkey, 0,decodedkey.length,"DES");
       return originkey;}
    
    
    
         public static void gen_key() throws NoSuchAlgorithmException{
         KeyGenerator kg=KeyGenerator.getInstance("DES");
         Key k=kg.generateKey();
         String encodedKey=Base64.getEncoder().encodeToString(k.getEncoded());
       try {
          FileWriter myWriter = new FileWriter("D://key.txt");
          myWriter.write(encodedKey);
    
          myWriter.close();
          System.out.println("Successfully wrote  key to the file.");
        } catch (IOException e) {
          System.out.println("An error occurred.");
          e.printStackTrace();
        }   

    }
         public static byte [] encrypt(String plain,Key k ) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
         {        
             Cipher cipher = Cipher.getInstance("DES"); 
            cipher.init(Cipher.ENCRYPT_MODE, k); 
             byte[] data = plain.getBytes(); 
            byte[] result = cipher.doFinal(data); 
           return result;
         } 
    }

when i run server then client i have this output

The date server is running...
javax.crypto.spec.SecretKeySpec@fffe78c8
[B@1412c2f
Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character 5b
    at java.util.Base64$Decoder.decode0(Base64.java:714)
    at java.util.Base64$Decoder.decode(Base64.java:526)
    at Server.Decrypt(Server.java:60)
    at Server.main(Server.java:48)
C:\Users\ASUS\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 11 seconds)

Upvotes: 0

Views: 1140

Answers (1)

Michael Fehr
Michael Fehr

Reputation: 6394

The error results of different formats of the encrypted text ("ciphertext"). On client side the output of the encrypt method is a byte array that get transferred via Socket to the server. On server side the input of the decryption method awaits a string in Base64-encoding.

So you can send the encrypted data as a byte array and leave out the decoding part OR you encode your byte array on client side with Base64 like

byte[] r;
r = encrypt("fatimaalzahrasha",k);
String rBase64 = Base64.getEncoder().encodeToString(r);
os.writeUTF(rBase64);

Upvotes: 1

Related Questions