Writing a code to decrypt message from a text file

1.8k Views Asked by At

I got this question where I got to write a class named DecryptMessage that reads a secret message stored in a file called Mymessage.txt and decrypt the message. I really have no idea how to start. Please anybody help me? Much appreciated.

Below is what I've done and more or less I manage to got the answer thanks to whoever have helped and just to share the answers.

package decryptmessage;

import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.*;

public class DecryptMessage {


public static void main(String[] args)
{
    int key = 10;
    FileWriter fWriter = null;
    BufferedWriter writer = null;
    try
    {
        File file = new File("C:\\Users\\Desktop\\Decrypted.txt");
        fWriter = new FileWriter(file.getAbsoluteFile());
        writer = new BufferedWriter(fWriter);
        //if file not exist, create a new file. If exist, delete the file and create a new file
         if (!file.exists())
        {
            file.delete();
            file.createNewFile();
        }
        else
        {
            file.createNewFile();
        }
    }
    catch(Exception e)
    {
         System.out.println("Unable to create file");
    }

    try
    {
        BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Desktop\\Mymessage.txt"));

        String line = "";

        while ((line = br.readLine()) != null)
        {
            writer.write(decrypt(line,key));
            writer.newLine();
        }
        if(br.readLine() == null)
        {
            writer.close();
        }
    }
    catch(Exception e)
    {
        System.out.println("Unable to write into file");
    }
}

private static String decrypt(String s, int key)
{
    String decrypt = "";
    for(int i = 0; i < s.length(); i++ )
    {
        decrypt +=(char) (s.charAt(i) + key);
    }
    return decrypt;
}

}

3

There are 3 best solutions below

0
On

I suggest you to first learn how to read and write onto files from here.

Then, take your text and encrypt it with a key. When you're reading it decrypt it with the same key.

Here's a small example on how to encryt and decrypt

EDIT

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class EncryptDecrypt {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String plainText = "This is the plain text";
    int key = 10;
    String encryptedText = encrypt(plainText, key);
    String decryptedText = decrypt(encryptedText, key);
    System.out.println("plain text: " + plainText);
    System.out.println("encrypted text: " + encryptedText );
    System.out.println("decrypted text: " + decryptedText);
    //==reading a plain text document
     // The name of the file to open.
    String readFileName = "c://temp//temp.txt";
    String writeFileName = "c://temp//encrypted.txt";
    // This will reference one line at a time
    String line = null;

    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = 
            new FileReader(readFileName);
        FileWriter fileWriter = 
                new FileWriter(writeFileName);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = 
            new BufferedReader(fileReader);
        //buffered writer
        BufferedWriter bufferedWriter =
                new BufferedWriter(fileWriter);

        while((line = bufferedReader.readLine()) != null) {
            String encrypted = encrypt(line, key);
            bufferedWriter.write(encrypted+"\n");
        }    

        // Always close files.
        bufferedReader.close();
        bufferedWriter.close();
    }
    catch(FileNotFoundException ex) {
        System.out.println(
            "Unable to open file '" + 
            readFileName + "'");                
    }
    catch(IOException ex) {
        System.out.println(
            "Error reading file '" 
            + readFileName + "'");                   
        // Or we could just do this: 
        // ex.printStackTrace();
    }

    //Now let us read the encrypted file and decrypt it
    // The name of the file to open.
    String fileName = "c://temp//encrypted.txt";
    System.out.println("The decrypted text is:");
    // This will reference one line at a time

    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = 
            new FileReader(fileName);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = 
            new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null) {
            System.out.println(decrypt(line,key));
        }    

        // Always close files.
        bufferedReader.close();            
    }
    catch(FileNotFoundException ex) {
        System.out.println(
            "Unable to open file '" + 
            fileName + "'");                
    }
    catch(IOException ex) {
        System.out.println(
            "Error reading file '" 
            + fileName + "'");                   
        // Or we could just do this: 
        // ex.printStackTrace();
    }

}


private static String decrypt(String s, int key) {
    // TODO Auto-generated method stub
    String decrypt = "";
    for(int i = 0; i < s.length(); i++ )
        decrypt +=(char) (s.charAt(i) + key);
    return decrypt;
}

private static String encrypt(String s, int key) {
    // TODO Auto-generated method stub
    String encrypt = "";
    for(int i = 0; i < s.length(); i++ )
        encrypt +=(char) (s.charAt(i) - key);
    return encrypt;
}

}

7
On

Just analyse the text with a bufferedReader

 try{
     // open input stream test.txt for reading purpose.
     BufferedReader br = new BufferedReader("c:/test.txt");
     while ((thisLine = br.readLine()) != null) {
        System.out.println(thisLine);
     }       
  }catch(Exception e){
     e.printStackTrace();
  }

} }

And while you're reading the text, just analyse every char and make it -10

 System.out.print(currentchar-10)

Seems like the easiest way to do it to me

0
On

Well there's not much to say, you should google every step you encounter. Do you know what a Class is ? If not, google it. Do you know how to read data from a file ? If not, google it. Lastly, you only need to manipulate characters, figure out what your "substracting 10" mean (alphabetical order ?), then it is quite easy in java.

Simpliest code sample :

        char c = 'c';
        System.out.println(c);
        c = (char) (c + 5);
        System.out.println(c); //is now h

There are multiple tutorials covering these, if you're still struggling your teacher should also be able to help you as long as you prove you have done some searches.