Encrypt and decrypt contents of a text file (Java)

4.2k Views Asked by At

I'm looking for some help with my program here. This program can encrypt and decrypt a phrase using DES symmetric cipher, based on CBC mode of operation.

What I am trying to do now is it to change it such that it can encrypt and decrypt the content of a text file using DES symmetric cipher using CBC mode of operation.

Can anyone help me out with this please?

Thank you!

import java.security.*;

import javax.crypto.*;

import java.security.spec.*;

import javax.crypto.spec.*;

import javax.crypto.spec.IvParameterSpec;



public class myProgram
{
  public static void main (String[] args) throws Exception
  {

    String text = "Hello World;

    SecureRandom sr = new SecureRandom();
    byte [] iv = new byte[8];
    sr.nextBytes(iv);
    IvParameterSpec IV = new IvParameterSpec(iv);
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    Key mykey = kg.generateKey();
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, mykey,IV);

    byte[] plaintext = text.getBytes("UTF8");



    byte[] ciphertext = cipher.doFinal(plaintext);

    System.out.println("\n\nCiphertext: ");
    for (int i=0;i<ciphertext.length;i++) {

        if (chkEight(i)) {
            System.out.print("\n");
        }
        System.out.print(ciphertext[i]+" ");
    }
1

There are 1 best solutions below

0
On BEST ANSWER

So you just want to know how to read and write to a file?

Take a look at apache.commons.io.FileUtils. It offers both methods for reading and writing strings from/to a file. Here are some examples:

// info.txt represents the path to the file
File someFile = new File("info.txt");

// Create String from File
try {
  String filecontent = FileUtils.readFileToString(someFile, Charset.defaultCharset());
  System.out.println(filecontent);

} catch (IOException e) {
  e.printStackTrace();
}

// Encode / Decode string here

// Write String to file     
try {
  FileUtils.writeStringToFile(someFile, "your new file content string", Charset.defaultCharset());
  System.out.println("Success!");

} catch (IOException e) {
  e.printStackTrace();
}

You might want to use a different Charset, depending on the charset of your text file.