In: Computer Science
in java
File encryption is the science of writing the contents of a file in a secret code. Write an encryption program that works like a filter, reading the contents of one file, modifying the data into a code, and then writing the coded contents out to a second file. The second file will be a version of the first file, but written in a secret code. Although there are complex encryption techniques, you should come up with a simple one of your own. For example, you could read the first file one character at a time, and add 10 to the character code of each character before it is written to the second file.
Write a second program that decrypts the file produced by the program. The decryption program should read the contents of the coded file, restore the data to its original state, and write it to another file.
Hint: Store the files in .txt format and use the readByte() and writeByte() methods.
Program:
input.txt:
Sample output:
EncryptedFile.txt
DecryptedFile.txt
Code to copy:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class EncryptFileData
{
public static void main(String args[]) throwsIOException, FileNotFoundException
{
String inputFileName="input.txt";
String outputFileName="EncryptedFile.txt";
String decryptFileName="DecryptedFile.txt";
byte codeValue;
Scanner sc=new Scanner(System.in);
//Accept code value from user
System.out.println("Enter the value of code");
codeValue=sc.nextByte();
//Encrypt the input file
encryptFileContent(inputFileName, codeValue,outputFileName);
//Decrypt the input file
decryptFileContent(outputFileName, codeValue,decryptFileName);
}
//function to encrypt the input file
private static void encryptFileContent(String inputFileName,
byte encodeValue, String outputFileName) throws IOException, FileNotFoundException{
File file = new File(inputFileName);
FileInputStream fin = newFileInputStream(file);
FileOutputStream fout = newFileOutputStream(outputFileName);
try{
while(fin.available() != 0){
int inData = fin.read();
//For every character in input add code value and
//write result to file "EncryptedFile.txt"
fout.write(inData+encodeValue);
}
}finally{
fin.close();
fout.close();
}
}
//function to decrypt the encrypted file
private static void decryptFileContent(String inputFileName,
byte encodeValue, String outputFileName) throws IOException, FileNotFoundException{
File file = new File(inputFileName);
FileInputStream fin = newFileInputStream(file);
FileOutputStream fout = newFileOutputStream(outputFileName);
try{
while(fin.available() != 0){
int inData = fin.read();
//For every character in encrypted file
//subtract the code value from each character and
//write it to file "DecryptedFile.txt"
fout.write(inData-encodeValue);
}
}finally{
fin.close();
fout.close();
}
}
}