Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8919569
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T06:03:51+00:00 2026-06-15T06:03:51+00:00

I’m trying to encrypt the contents of one file into another file using a

  • 0

I’m trying to encrypt the contents of one file into another file using a passphrase in Java. The file is getting read to a byte array, encrypted to another byte array, and then written to the new file. Unfortunately, when I try to reverse the encryption, the output file gets decrypted as garbage.

I strongly suspect that the issue has to do with generating an identical key every time the same passphrase is used. I wrote a testing method that dumps the key into a file whenever one gets generated. The key is recorded both directly and in encoded form. The former is identical every time, but the latter is always different for some reason.

In all honesty, I don’t know a great deal about encryption methods, especially in Java. I only need the data to be moderately secure, and the encryption doesn’t have to withstand an attack from anyone with significant time and skills. Thanks in advance to anyone who has advice on this.

Edit: Esailija was kind enough to point out that I was always setting the cipher with ENCRYPT_MODE. I corrected the problem using a boolean argument, but now I’m getting the following exception:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

That sounds to me like the passphrase isn’t being used properly. I was under the impression that “PBEWithMD5AndDES” would hash it into a 16 byte code, which most certainly is a multiple of 8. I’m wondering why the key generates and gets used just fine for encryption mode, but then it complains when trying to decrypt under the exact same conditions.

import java.various.stuff;

/**Utility class to encrypt and decrypt files**/
public class FileEncryptor {
    //Arbitrarily selected 8-byte salt sequence:
    private static final byte[] salt = {
        (byte) 0x43, (byte) 0x76, (byte) 0x95, (byte) 0xc7,
        (byte) 0x5b, (byte) 0xd7, (byte) 0x45, (byte) 0x17 
    };

    private static Cipher makeCipher(String pass, Boolean decryptMode) throws GeneralSecurityException{

        //Use a KeyFactory to derive the corresponding key from the passphrase:
        PBEKeySpec keySpec = new PBEKeySpec(pass.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        //Create parameters from the salt and an arbitrary number of iterations:
        PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 42);

        /*Dump the key to a file for testing: */
        FileEncryptor.keyToFile(key);

        //Set up the cipher:
        Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");

        //Set the cipher mode to decryption or encryption:
        if(decryptMode){
            cipher.init(Cipher.ENCRYPT_MODE, key, pbeParamSpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, key, pbeParamSpec);
        }

        return cipher;
    }


    /**Encrypts one file to a second file using a key derived from a passphrase:**/
    public static void encryptFile(String fileName, String pass)
                                throws IOException, GeneralSecurityException{
        byte[] decData;
        byte[] encData;
        File inFile = new File(fileName);

        //Generate the cipher using pass:
        Cipher cipher = FileEncryptor.makeCipher(pass, false);

        //Read in the file:
        FileInputStream inStream = new FileInputStream(inFile);
        decData = new byte[(int)inFile.length()];
        inStream.read(decData);
        inStream.close();

        //Encrypt the file data:
        encData = cipher.doFinal(decData);


        //Write the encrypted data to a new file:
        FileOutputStream outStream = new FileOutputStream(new File(fileName + ".encrypted"));
        outStream.write(encData);
        outStream.close();
    }


    /**Decrypts one file to a second file using a key derived from a passphrase:**/
    public static void decryptFile(String fileName, String pass)
                            throws GeneralSecurityException, IOException{
        byte[] encData;
        byte[] decData;
        File inFile = new File(fileName);

        //Generate the cipher using pass:
        Cipher cipher = FileEncryptor.makeCipher(pass, true);

        //Read in the file:
        FileInputStream inStream = new FileInputStream(inFile);
        encData = new byte[(int)inFile.length()];
        inStream.read(encData);
        inStream.close();

        //Decrypt the file data:
        decData = cipher.doFinal(encData);

        //Write the decrypted data to a new file:
        FileOutputStream target = new FileOutputStream(new File(fileName + ".decrypted.txt"));
        target.write(decData);
        target.close();
    }

    /**Record the key to a text file for testing:**/
    private static void keyToFile(SecretKey key){
        try {
            File keyFile = new File("C:\\keyfile.txt");
            FileWriter keyStream = new FileWriter(keyFile);
            String encodedKey = "\n" + "Encoded version of key:  " + key.getEncoded().toString();
            keyStream.write(key.toString());
            keyStream.write(encodedKey);
            keyStream.close();
        } catch (IOException e) {
            System.err.println("Failure writing key to file");
            e.printStackTrace();
        }

    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T06:03:53+00:00Added an answer on June 15, 2026 at 6:03 am

    You are using the Cipher.ENCRYPT_MODE for both, decrypting and encrypting. You should use Cipher.DECRYPT_MODE for decrypting the file.

    That has been fixed, but your boolean is wrong. It should be true for encrypt and false for decrypt. I would strongly recommend against using false/true as function arguments and always use enum like Cipher.ENCRYPT… moving on

    Then you are encrypting to .encrypted file, but trying to decrypt the original plain text file.

    Then you are not applying padding to encryption. I am surprised this actually has to be done manually,
    but padding is explained here. The padding scheme PKCS5 appeared to be implicitly used here.

    This is full working code, writing encrypted file to test.txt.encrypted, and decrypted file to test.txt.decrypted.txt.
    Adding padding in encryption and removing it in decryption is explained in the comments.

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    import java.util.Arrays;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    
    public class FileEncryptor {
    
        public static void main( String[] args ) {
    
            try {
                encryptFile( "C:\\test.txt", "password" );
                decryptFile( "C:\\test.txt", "password" );
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (GeneralSecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        //Arbitrarily selected 8-byte salt sequence:
        private static final byte[] salt = {
            (byte) 0x43, (byte) 0x76, (byte) 0x95, (byte) 0xc7,
            (byte) 0x5b, (byte) 0xd7, (byte) 0x45, (byte) 0x17 
        };
    
        private static Cipher makeCipher(String pass, Boolean decryptMode) throws GeneralSecurityException{
    
            //Use a KeyFactory to derive the corresponding key from the passphrase:
            PBEKeySpec keySpec = new PBEKeySpec(pass.toCharArray());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(keySpec);
    
            //Create parameters from the salt and an arbitrary number of iterations:
            PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 42);
    
            /*Dump the key to a file for testing: */
            FileEncryptor.keyToFile(key);
    
            //Set up the cipher:
            Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
    
            //Set the cipher mode to decryption or encryption:
            if(decryptMode){
                cipher.init(Cipher.ENCRYPT_MODE, key, pbeParamSpec);
            } else {
                cipher.init(Cipher.DECRYPT_MODE, key, pbeParamSpec);
            }
    
            return cipher;
        }
    
    
        /**Encrypts one file to a second file using a key derived from a passphrase:**/
        public static void encryptFile(String fileName, String pass)
                                    throws IOException, GeneralSecurityException{
            byte[] decData;
            byte[] encData;
            File inFile = new File(fileName);
            //Generate the cipher using pass:
            Cipher cipher = FileEncryptor.makeCipher(pass, true);
    
            //Read in the file:
            FileInputStream inStream = new FileInputStream(inFile);
    
            int blockSize = 8;
            //Figure out how many bytes are padded
            int paddedCount = blockSize - ((int)inFile.length()  % blockSize );
    
            //Figure out full size including padding
            int padded = (int)inFile.length() + paddedCount;
    
            decData = new byte[padded];
    
    
            inStream.read(decData);
    
            inStream.close();
    
            //Write out padding bytes as per PKCS5 algorithm
            for( int i = (int)inFile.length(); i < padded; ++i ) {
                decData[i] = (byte)paddedCount;
            }
    
            //Encrypt the file data:
            encData = cipher.doFinal(decData);
    
    
            //Write the encrypted data to a new file:
            FileOutputStream outStream = new FileOutputStream(new File(fileName + ".encrypted"));
            outStream.write(encData);
            outStream.close();
        }
    
    
        /**Decrypts one file to a second file using a key derived from a passphrase:**/
        public static void decryptFile(String fileName, String pass)
                                throws GeneralSecurityException, IOException{
            byte[] encData;
            byte[] decData;
            File inFile = new File(fileName+ ".encrypted");
    
            //Generate the cipher using pass:
            Cipher cipher = FileEncryptor.makeCipher(pass, false);
    
            //Read in the file:
            FileInputStream inStream = new FileInputStream(inFile );
            encData = new byte[(int)inFile.length()];
            inStream.read(encData);
            inStream.close();
            //Decrypt the file data:
            decData = cipher.doFinal(encData);
    
            //Figure out how much padding to remove
    
            int padCount = (int)decData[decData.length - 1];
    
            //Naive check, will fail if plaintext file actually contained
            //this at the end
            //For robust check, check that padCount bytes at the end have same value
            if( padCount >= 1 && padCount <= 8 ) {
                decData = Arrays.copyOfRange( decData , 0, decData.length - padCount);
            }
    
            //Write the decrypted data to a new file:
    
    
    
            FileOutputStream target = new FileOutputStream(new File(fileName + ".decrypted.txt"));
            target.write(decData);
            target.close();
        }
    
        /**Record the key to a text file for testing:**/
        private static void keyToFile(SecretKey key){
            try {
                File keyFile = new File("C:\\keyfile.txt");
                FileWriter keyStream = new FileWriter(keyFile);
                String encodedKey = "\n" + "Encoded version of key:  " + key.getEncoded().toString();
                keyStream.write(key.toString());
                keyStream.write(encodedKey);
                keyStream.close();
            } catch (IOException e) {
                System.err.println("Failure writing key to file");
                e.printStackTrace();
            }
    
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am reading a book about Javascript and jQuery and using one of the
I am trying to render a haml file in a javascript response like so:
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have thousands of HTML files to process using Groovy/Java and I need to
I'm making a simple page using Google Maps API 3. My first. One marker
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.