0

I am trying to read user input from console using Scanner but it only reads my first input, and then on my second input it closes my program.

Here is my code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;

public class RSAFileEncryption 
{   
    public static final String ALGORITHM = "RSA";
    public static final String PRIVATE_KEY_FILE = "C:\\keys\\private.key";
    public static final String PUBLIC_KEY_FILE = "C:\\keys\\public.key";

    public static byte[] encrypt(String text, PublicKey key) 
    {
        byte[] cipherText = null;
        try 
        {
          // get an RSA cipher object and print the provider
          final Cipher cipher = Cipher.getInstance(ALGORITHM);
          // encrypt the plain text using the public key
          cipher.init(Cipher.ENCRYPT_MODE, key);
          cipherText = cipher.doFinal(text.getBytes());
        } 
        catch (Exception e) 
        {
          e.printStackTrace();
        }
        return cipherText;
    }

     public static String decrypt(byte[] text, PrivateKey key) 
     {         
        byte[] dectyptedText = null;
        try 
        {
          // get an RSA cipher object and print the provider
          final Cipher cipher = Cipher.getInstance(ALGORITHM);

          // decrypt the text using the private key
          cipher.init(Cipher.DECRYPT_MODE, key);
          dectyptedText = cipher.doFinal(text);

        } 
        catch (Exception ex) 
        {
          ex.printStackTrace();
        }

        return new String(dectyptedText);
    }

    public static void generateKey()
    {
        try 
         {
            final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
            keyGen.initialize(1024);
            final KeyPair key = keyGen.generateKeyPair();

            File privateKeyFile = new File(PRIVATE_KEY_FILE);
            File publicKeyFile = new File(PUBLIC_KEY_FILE);

            // Create files to store public and private key
            if (privateKeyFile.getParentFile() != null) 
            {
                privateKeyFile.getParentFile().mkdirs();
            }
            privateKeyFile.createNewFile();

            if (publicKeyFile.getParentFile() != null) 
            {
                publicKeyFile.getParentFile().mkdirs();
            }
            publicKeyFile.createNewFile();

            // Saving the Public key in a file
            ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                new FileOutputStream(publicKeyFile));

            publicKeyOS.writeObject(key.getPublic());
            publicKeyOS.close();

            // Saving the Private key in a file
            ObjectOutputStream privateKeyOS = new ObjectOutputStream(
                new FileOutputStream(privateKeyFile));
            privateKeyOS.writeObject(key.getPrivate());
            privateKeyOS.close();
          } 
         catch (Exception e) 
         {
            e.printStackTrace();
         }
    }

    public static boolean areKeysPresent() 
    {
        File privateKey = new File(PRIVATE_KEY_FILE);
        File publicKey = new File(PUBLIC_KEY_FILE);

        if (privateKey.exists() && publicKey.exists()) 
        {
            return true;
        }

        return false;
     }

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        try
        {
            if (!areKeysPresent()) 
            {
                  generateKey();
            }

            int choice;

            while(true)
            {
                System.out.println("1 - Generate key.");
                System.out.println("2 - Encrypt file.");
                System.out.println("3 - Decrypt file.");
                System.out.println("0 - Exit.");
                System.out.print("\n>> ");
                choice = sc.nextInt();

                if(choice == 1)
                    generateKey();

                else if(choice == 2)
                {
                    if (!areKeysPresent()) 
                    {
                        generateKey();
                    }

                    String line;

                    System.out.print("Enter path to file: ");
                    String fileName = sc.nextLine();

                    ObjectInputStream inputStream = null;
                    inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
                    final PublicKey publicKey = (PublicKey) inputStream.readObject();

                    BufferedReader br = new BufferedReader(new FileReader(fileName));

                    String tmp = fileName + ".encrypted";

                    FileWriter fw = new FileWriter(tmp);

                    while((line = br.readLine()) != null)
                    {
                        String s = encrypt(line, publicKey).toString();
                        fw.write(s);
                    }
                }
                else if(choice == 3)
                {
                    if (!areKeysPresent()) 
                    {
                        System.out.println("There are no keys. Sorry but the file cant be decrypted.");
                    }

                    String line;

                    System.out.print("Enter path to file: ");
                    String fileName = sc.nextLine();

                    ObjectInputStream inputStream = null;
                    inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
                    final PrivateKey privateKey = (PrivateKey) inputStream.readObject();

                    BufferedReader br = new BufferedReader(new FileReader(fileName));

                    FileWriter fw = new FileWriter(fileName);

                    String s;
                    while((line = br.readLine()) != null)
                    {
                        s = decrypt(line.getBytes(), privateKey);
                        fw.write(s);
                    }
                }

                else
                    System.exit(0);
            }
        }
        catch(Exception e)
        {
            e.getStackTrace();
        }
    }
}
3
Contributors
2
Replies
23
Views
4 Years
Discussion Span
Last Post by IIM
0

Your e.getStackTrace on line 208 is presumably a mis-type for e.printStackTrace.
Fix that and see if you are getting any exceptions

1

instead of this,

choice = sc.nextInt();//line 141

try with using,

choice = Integer.parseInt(sc.nextLine());

As per my thinking,the error is because of this,as when you press enter after entering number,that is what is taken as filename.Changing into this will solve your issue here.

Votes + Comments
Yes, looks lik ethe standard nextInt+nextLine gotcha
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.