Forums Register Login

Java Encrypt and decrypt file

+Pie Number of slices to send: Send
I am trying to write a program that asks a user for a file. I need to encrypt and or decrypt the text that is input. I don't know if I need to import another class, or if I can just write a line or two of code that has Encrypt.txt and Decrypt.txt I have attached what I have so far, please feel free to help me where I am going wrong. Thank you in advance.
+Pie Number of slices to send: Send
What do you mean by "encrypt"? There are probably thousands of encryption schemes, each with varying degrees of complexity in terms of both coding and cracking.

It looks to my like right now, you are reading a file, one character at a time, and then printing it out again, only without spaces. Technically, that is an encryption scheme, although not a very secure one. One of the problems you will have is reversing this - how will you know where to put them back?

Many encryption schemes will encode more than one character at a time. for example, you take 3 bytes of data (24 bits), break it up into 4 6-bit chunks, then write out those as four alpha-numeric + a few symbolic values (52 upper/lower case letters + 10 digits plus 4 symbols for the 64 possible 6-bit numbers).

Note that doing something like this is not a simple "line or two of code".

So, the real question is...What encryption process do you want to use? You can't really do much of anything else until you decide what your algorithm will be.
+Pie Number of slices to send: Send
Well what I need to do is write my own encryption and decryption funtion into this program. I used the eliminating white space just as a "practice". What I would like to do is use ASCII and increment the letters to shift. I just don't know where to insert these functions into this program. If I have my understanding correctly, the ArrayList will assist in encrypt and decrypt correct? I have a couple different examples that I can give too.

char ch = ...
if (ch >= 'A' && ch < 'Z') ch++;
else if (ch == 'Z') ch = 'A';
else if (ch >= 'a' && ch < 'z') ch++;
else if (ch == 'z') ch = 'z';

My question on this little method is how would I decrypt? Then I have this one,

Assuming I want to shift all letters by n:
((letter - 'A' + n) % 26) + 'A'

And to decode:
((letter - 'A' + 26 - n) % 26) + 'A'

where would I insert these lines of code? I am just trying different ways of encrypt and decrypt am open to suggestion

I am thinking that the char method would work better for the code that I have written so far correct?
+Pie Number of slices to send: Send
Welcome to the Ranch

I am afraid % 26 won’t work, because 'A' is 0x41 (65) and 'Z' is 0x5a (90). You might get % 0x20(32) to work, but only with the 26 un‑accented letters used in English.
+Pie Number of slices to send: Send
 

Adam Stever wrote:I have a couple different examples that I can give too.
char ch = ...
if (ch >= 'A' && ch < 'Z') ch++;
else if (ch == 'Z') ch = 'A'; ...


Well, strictly speaking what you're doing there is a rotation, and to be honest, I like it better than your second example, since it's impossible for it to generate any "collisions" (values that are impossible to decrypt because you can't be sure what value created them).

My suggestion: For a simple "translation" cypher like yours, I'd keep the methodology separate from the translation. There are only 65,000-odd possible values for a char, so every one of them will fit into an array that takes up 128K, which, as we know is peanuts these days.
With two of those arrays: an "encrypt" and a "decrypt", you can implement any translation you want by simply plugging the appropriate value into the correct position in the "encrypt" array and its reverse in the "decrypt". And if you're only interested in encrypting standard ASCII, the tables only need to contain 128 characters rather than 65,000.

That way, your methodology is only used once - to populate the tables. Once you have those, translation is as simple as:One thing to remember: You have to put ALL possible values into the array - even the ones you don't intend to translate - or you need some sort of sentinel value ('\u0000' (0) is probably easiest, since it's the default value for a char[] element and it's almost never found in text), viz:HIH

Winston
+Pie Number of slices to send: Send
I absolutley love the information that people are offering in this forum. However, I have a couple more questions, which is I like the char example, but where would that get written into my code? It would have to be in side the the try, yes? and then instead of the [c] in the public char [c] would I insert the file name that needs to be encrypted and decrypted? and then my second question, is how to I import the ASCII tables, and how would i write them into the code? I understand that I would be working with 128 characters as opposed to 65,000. I am having trouble containg my excitement with all this great information. The help that I have received so far is great. I know that everybody may not be as undestanding of a "Greenhorn " but I do appreciate the ones who are.
+Pie Number of slices to send: Send
So judging from information that I am finding via books and online, wouldn't my encrypt and decrypt function go after the if statement? Due to the fact that this function is after every character is going to be read in and the encrypt and decrypt functions should take place here correct? I am just trying to piece this thing together, I have the program running so that at this point the program will eliminate the whitespace (obviously) however I am struggling on how to input the encrypt and decrypt functions, and where they would go. Usually the user would know if the file is encrypted or not, but what I am looking for is how to decrypt if the file is encypted and encrypt if the file is decrypted. Please help.
+Pie Number of slices to send: Send
 

Adam Stever wrote:Usually the user would know if the file is encrypted or not, but what I am looking for is how to decrypt if the file is encypted and encrypt if the file is decrypted. Please help.


Easiest is probably to include a simple header value that tells your program that the file is encrypted ("$ENCRYPTED:" ?). Obviously, you'd want to use something that isn't likely to occur at the start of a normal file, but since this only a class exercise, you probably don't have to get too fancy.

Winston
+Pie Number of slices to send: Send
Okay, so this is a program that I am trying to write, and the goall here is to give the user an option to ecrypt or decrypt their file, and the form of encryption that I would like to use is just incrment +1 and just move letters by (Obvously) I know that this program is not working I am asking for help and insight into what I need to change and improve. Please offer any advice into which direction I need to keep moving please.





import java.util.*;
import java.io.*;
import java.util.InputMismatchException;

public class FileFun{

public static void main (String[]args){

PrintWriter fileOut; // print out to a file
Scanner fileIn; // to read a file in
Scanner console = new Scanner (System.in);
String fileName = ""; // variable that allow us to store the file name
String line = ""; // enable us to read one line at a time
int function = 0;// 1 to encrypt 2 to decrypt
char ch[]; // temp storing for each character
ArrayList<String> name = new ArrayList<String>(); // stores multiple characters and assists in ecrypting and decrypting

try{
// get file name and either encrypt or decrypt
System.out.println("Please enter a file name");
fileName = console.nextLine();
System.out.println("Would you like to Encyrpt or Decrypt your file? \n Press 1 to Encrypt or 2 to Decrypt");
function = console.nextInt();
fileIn = new Scanner (new FileReader (fileName));
fileOut = new PrintWriter("Java Encrypt/Decrypt");

if (function == 1)

while (fileIn.hasNextLine())
{
line = fileIn.nextLine();

for (int i=0; i<fileName.length(); i++)
{
if (fileName [i] = ch);

{
System.out.println(fileName [i+1]);
}

else (fileName!= ch);
{
System.out.println(fileName [i-1]);
}
}// end for

}// end while

fileOut.close();

}// end try
catch (FileNotFoundException e)
{
System.out.println("Error:" + e.getMessage());
}


}// end main

}// end class
+Pie Number of slices to send: Send
Please use the code button and avoid such long lines. Please don’t ask the same question twice. I have closed your other thread, even though you got some useful information there.

The ideal length of a main method is one statement. That means there are at least 25 lines which ought to be moved into other methods.
+Pie Number of slices to send: Send
Thank you for the heads up, My apologies. So what I am trying to do with this program is give the user the option to either encrypt or decrypt their file that they are going to enter. I am trying to do this using a while loop, for loop, if and else statements, Here is what I have so far,



I have asked the user to enter 1 to encrypt their code or 2 to decrypt their code. Thus, if 1 then carry out the function of 1, else...........
A second issue I am having is I am reading in the users file as a string, and java is saying I need to put it into an array, here is what I have,


I am under the impressiong that the file would be in an array due to the fact that I am reading the file that is entered into the array string? Obviously I am wrong, please help me...
+Pie Number of slices to send: Send
Don’t know, because I can’t read unformatted code. If you use the button, you can sort out the indentation and the long lines, then we can all read the code
+Pie Number of slices to send: Send
 

Adam Stever wrote:Thank you for the heads up...


Adam, you need to re-read the UseCodeTags page thoroughly. You've made a basic mistake. I also advise checking your posts with the Preview button before you post.

Also: you don't need to re-post everything every time (unless it's new or different, obviously). To add code tags (or correct your current ones), just use the Edit button.

Winston
+Pie Number of slices to send: Send
The problem was that you hadn’t written the code tags correctly. Don’t try to do it all yourself; the “ccode” button is a lot quicker and more acccurate. Now I have corrected the code tags, and got rid of the longest lines, you can see how much better it looks.

You have all sorts of things wrong with that code. You have even introduced errors since you first posted.
Don’t use \n in Strings, even though you see that in the books. You will see what you ought to use here, just below half‑way down the page.
The whole idea of programming is to divide and rule. You want several different things done, and each “thing done” need to be in its own method. You are confusing three things: reading from a file, writing to a file, and encrypting the text.
Set up a class to do this in, maybe called FileEncrypter.
Set up a method which reads from a file, and start by getting it to display the lines on screen. Then later, you can add them to the List. That will take ages, well over ten minutes, particularly if you search the Ranch and find posts which tell you how to do it. Remember, you must close all readers and writers except those using System.in, System.err or System.out. You must use a finally block for the closing, or try with resources, the latter being only available in Java7.
Now set up a method which writes your results back into the output file. When you realise that file writing is just the same as file reading, but in reverse, that will take even longer to achieve. Allow well over 5 minutes to write that. Now run your reading and writing method until you are happy they work.

Now you have got that working, you can iterate through your List of lines and send each line to be encrypted. I suggest you add each line to another List. Now write a method like thisIf you are using chars and char[]s, then encryptedLetters would be a char[].

And you needn’t expect any more hints!
+Pie Number of slices to send: Send
I shall let you find the error I inadvertently introduced into your posted code. Sorry.
+Pie Number of slices to send: Send
Is your inadvertant mistake, missing the "a" in private? or is it the private instead of public? And yes I know my programming is very rough around the edges, I know that I am not as refined as some maybe even most but I try hard. What I would like to do is to read the file that is input, into an array list, Which I think that I have done, then later I will increment the file +1, I am having trouble in the else statement, and the decrement part of it. Here are some of the most recent chages/additions to my program.



+Pie Number of slices to send: Send
I can’t remember what the mistake was. I definitely meant private, though.
You are simply repeating the mistakes you were told about last week. That code looks as if you are guessing about what to do. I suggest you delete the entire block of code you just posted and reduce it to this . . . where input and output are List<String>s.
Use sheet of paper to write down how the encrypt and decrypt methods are supposed to work before you write anything.
+Pie Number of slices to send: Send
 

Adam Stever wrote:And yes I know my programming is very rough around the edges, I know that I am not as refined as some maybe even most but I try hard.


Yes, but you don't seem to want to listen. I've already explained how you could do it, but it means thinking about the problem and breaking up your code into manageable chunks (ie, methods).

As Campbell is fond of saying (and he's quite right): The ideal main() method is 1 line long; and in your case, it certainly shouldn't be more than about 10.
But in order to get there, you need to write down the logical steps needed to solve the problem. Right now, you just seem to be trying to force a solution through coding and it won't work.

I've even suggested a solution by which your program could encrypt or decrypt automatically, which would save you all the code for getting an option value from the user. Another thing that's worth remembering is that allowing the user to choose an option could let them encrypt an encrypted file, or try to decrypt one that's not encrypted.

Winston
+Pie Number of slices to send: Send
Thank you Winston and Ritchie and everybody else who input on my post, your input helped me alot, I ended up using the last format that ritchie gave, and utilized (due to the fact that I had to use information from "the book" I went with if statements with try catch, in both statements. Thank you for your help, I appreciate your tolerance and look forward to more posting.
+Pie Number of slices to send: Send
 

Adam Stever wrote:Thank you for your help, I appreciate your tolerance and look forward to more posting.


You're welcome. Hope to see you back soon.

Winston
+Pie Number of slices to send: Send
 

Winston Gutkowski wrote: . . . You're welcome. Hope to see you back soon. . . .

Agree. Me too
Uh oh, we're definitely being carded. Here, show him this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 14918 times.
Similar Threads
Program Help
Compiler class to read file and parse in Java
Need help with RSA Encryption
Why Arraylist gets cleard after being put to gether in a method?
java application using swing
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 14:39:17.