Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing encrypt - decrypt program using Java [duplicate]

Tags:

java

I was asked to write a program that encrypts a file by adding 5 to every byte of it and then write another program to decrypt the file. And here is the program I wrote. But it doesn't work. It encrypted a file successfully but then could not restore it back to the origin. The result of the decryption is just a file with some weird symbols in it.

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class CryptingFile 
{
    public static void main(String[] args)
    {               
        if(args.length != 3 || (args[2].compareTo("-en") != 0 && args[2].compareTo("-de") != 0))
        {
            System.out.println("Usage: sourceFile targetFile -<option>");
            System.out.println("<option>: ");
            System.out.println("    en :            encrypt");
            System.out.println("    de:             decrypt");
            System.exit(0);
        }

        try 
        {
            File fileInput = new File(args[0]);
            File fileOutput = new File(args[1]);

            FileInputStream input = new FileInputStream(fileInput);
            FileOutputStream output = new FileOutputStream(fileOutput);

            if(args[2] == "-en")
            {
                int value;

                while((value = input.read()) != -1)
                    output.write(value + 5);

            }
            else
            {
               int value;

               while((value =  input.read()) != -1)
                    output.write(value - 5);


            }


            input.close();
            output.close();


        } 
        catch (FileNotFoundException ex) 
        {
            System.out.println("Error " + args[0] + " not found");
        } catch (IOException ex) 
        {
            System.out.println("Error reading file");
        }


    }
}

This is a result it should look like:

This is a test file.

But it looks something like this:

J^_i_iWj[ij_b[$

like image 640
Minh Le Avatar asked Sep 29 '26 07:09

Minh Le


1 Answers

Replace

if(args[2] == "-en")

with

if(args[2].equals("-en"))

because

== used to compare whether they are the same object

.equals() used to compare the value of the object.

like image 123
ashiquzzaman33 Avatar answered Sep 30 '26 21:09

ashiquzzaman33



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!