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 6137739
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T17:45:52+00:00 2026-05-23T17:45:52+00:00

I’m currently working on a function that encrypt/decrypts a specific file with a secret

  • 0

I’m currently working on a function that encrypt/decrypts a specific file with a secret key. I have written three classes, one which generates a key, one which encrypts a file with the key and one that decrypts.

Generating the key and encrypting the file works fine, but when I try to decrypt the file, an exception is thrown at line: c.init(Cipher.DECRYPT_MODE, keySpec);:

java.security.InvalidKeyException: Parameters missing

I take it I’ve done something wrong when streaming the secret key to my byte[] or something is wrong when decrypting the file.

Quick explanation of the three classes: KeyHandler creates a AES key and stores it on the harddrive. The name of the key/plaintext/encrypted/decrypted files is currently hardcoded for testing purposes.

EncryptionHandler transfers a .txt file on the disk into bytes, encrypts the file with the secret key and then writes the encrypted bytes to the disk using CipherOutputStream.

DecryptionHandler of course does the opposite of EncryptionHandler.

Here’s the code:

    public class KeyHandler {
        Scanner scan = new Scanner(System.in);

        public KeyHandler(){
            try {
                startMenu();
            } catch (Exception e) {
                System.out.println("fel någonstanns :)");
            }
        }

        public void startMenu() throws Exception{

            System.out.println("Hej. Med detta program kan du generera en hemlig nyckel"+"\n"+"Vill du:"+"\n"+ "1. Generera en nyckel"+"\n"+"2. Avsluta");
            int val=Integer.parseInt(scan.nextLine());
        do{ 
            switch (val){
            case 1: generateKey(); break;
            case 2: System.exit(1);

            default: System.out.println("Du måste välja val 1 eller 2");
            }
        }
            while (val!=3);
        }

        public void generateKey() throws Exception{
            try {
                KeyGenerator gen = KeyGenerator.getInstance("AES");
                gen.init(128);

                SecretKey key=gen.generateKey();
                byte[] keyBytes = key.getEncoded();
                System.out.print("Ge nyckeln ett filnamn: ");
                String filename = scan.next();
                System.out.println("Genererar nyckeln...");
                FileOutputStream fileOut = new FileOutputStream(filename);
                fileOut.write(keyBytes);
                fileOut.close();
                System.out.println("Nyckeln är genererad med filnamnet: "+filename+"...");
                System.exit(1);
                 } catch (NoSuchAlgorithmException e) {
                    }

        }

        public static void main(String[] args){
            new KeyHandler();
        }

    }


    public class EncryptHandler {
        private String encryptedDataString;
        private Cipher ecipher; 

        AlgorithmParameterSpec paramSpec;
        byte[] iv;

        public EncryptHandler(String dataString, String secretKey, String encryptedDataString){
            this.encryptedDataString=encryptedDataString;
            try {
                encryptFile(dataString, secretKey);
            } catch (Exception e) {

            }
        }

            public void encryptFile(String dataString, String secretKey) throws Exception{

                    FileInputStream fis = new FileInputStream(secretKey);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    int theByte = 0;
                    while ((theByte = fis.read()) != -1)
                    {
                      baos.write(theByte);
                    }
                    fis.close();

                    byte[] keyBytes = baos.toByteArray();
                    baos.close();
                    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

                try 
                { 
                ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
                ecipher.init(Cipher.ENCRYPT_MODE, keySpec);     

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

                System.out.println("Encrypting file...");
                try 
                { 

                    encryptStream(new FileInputStream(dataString),new FileOutputStream(encryptedDataString)); 
                }
                catch(Exception e){
                e.printStackTrace();
                }

                }
    public void encryptStream(InputStream in, OutputStream out){
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                byte[] buf = new byte[1024]; 
                try { 
                out = new CipherOutputStream(out, ecipher); 

             // read the cleartext and write it to out
                int numRead = 0; 
                while ((numRead = in.read(buf)) >= 0) {
                out.write(buf, 0, numRead); 

                }
                bOut.writeTo(out);
                out.close();
                bOut.reset();

                } 
                catch (java.io.IOException e) 
                { 
                } 

                }


        public static void main(String[] args){
            String data = "test.txt";
            String keyFileName="a";
            String encryptedFile="krypterad.txt";
            //String encryptedFile =args[2];
            new EncryptHandler(data, keyFileName, encryptedFile);
        }

    }


public class DecryptHandler {
    public DecryptHandler(){

    try {
        decryptFile();
    } catch (Exception e) {
        System.out.println("något gick fel :) ");
        }
    }


    public void decryptFile()throws Exception{
        byte[] buf = new byte[1024]; 
        String keyFilename = "hemlig";
        FileInputStream fis = new FileInputStream(keyFilename);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int theByte = 0;
        while ((theByte = fis.read()) != -1)
        {
          baos.write(theByte);
        }
        fis.close();

        byte[] keyBytes = baos.toByteArray();
        baos.close();
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");


        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
                System.out.println("här");
        c.init(Cipher.DECRYPT_MODE, keySpec); 

        System.out.println("Decrypting file...");
        try{
        decryptStream(new FileInputStream("krypterad.txt"),new FileOutputStream("Dekryperad.txt"), c, buf);
        }
            catch (java.io.IOException e){

            }
            System.out.println("File decrypted!");
        }
    public void decryptStream(InputStream in, OutputStream out, Cipher dcipher, byte[] buf){
        try 
        { 

        in = new CipherInputStream(in, dcipher); 

        // Read in the decrypted bytes and write the cleartext to out 
        int numRead = 0; 


        while ((numRead = in.read(buf)) >= 0) 
        { 
        out.write(buf, 0, numRead);

        } 
        out.close();


        } 
        catch (java.io.IOException e){ 

        } 
    } 
    public static void main(String[]args){
        new DecryptHandler();
    }
}
  • 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-05-23T17:45:52+00:00Added an answer on May 23, 2026 at 5:45 pm

    If you use a block-chaining mode like CBC, you need to provide an IvParameterSpec to the Cipher as well.

    So you can initialize an IvParameterSpec like this:

        // build the initialization vector.  This example is all zeros, but it 
        // could be any value or generated using a random number generator.
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);
    

    Then for encryption, change your code where you init the cipher to this:

    ecipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
    

    And where you decrypt:

    c.init(Cipher.DECRYPT_MODE, keySpec, ivspec);
    

    So your complete code should look like this (It works for me):

        public class KeyHandler {
    
        Scanner scan = new Scanner(System.in);
    
        public KeyHandler() {
            try {
                startMenu();
            } catch (Exception e) {
                System.out.println("fel någonstanns :)");
            }
        }
    
        public void startMenu() throws Exception {
    
            System.out.println("Hej. Med detta program kan du generera en hemlig nyckel" + "\n" + "Vill du:" + "\n" + "1. Generera en nyckel" + "\n" + "2. Avsluta");
            int val = Integer.parseInt(scan.nextLine());
            do {
                switch (val) {
                    case 1:
                        generateKey();
                        break;
                    case 2:
                        System.exit(1);
    
                    default:
                        System.out.println("Du måste välja val 1 eller 2");
                }
            } while (val != 3);
        }
    
        public void generateKey() throws Exception {
            try {
                KeyGenerator gen = KeyGenerator.getInstance("AES");
                gen.init(128);
    
                SecretKey key = gen.generateKey();
                byte[] keyBytes = key.getEncoded();
                System.out.print("Ge nyckeln ett filnamn: ");
                String filename = scan.next();
                System.out.println("Genererar nyckeln...");
                FileOutputStream fileOut = new FileOutputStream(filename);
                fileOut.write(keyBytes);
                fileOut.close();
                System.out.println("Nyckeln är genererad med filnamnet: " + filename + "...");
                System.exit(1);
            } catch (NoSuchAlgorithmException e) {
            }
    
        }
    
        public static void main(String[] args) {
            new KeyHandler();
        }
    }
    
    public class EncryptHandler {
    
        private String encryptedDataString;
        private Cipher ecipher;
        AlgorithmParameterSpec paramSpec;
        byte[] iv;
    
        public EncryptHandler(String dataString, String secretKey, String encryptedDataString) {
            this.encryptedDataString = encryptedDataString;
            try {
                encryptFile(dataString, secretKey);
            } catch (Exception e) {
            }
        }
    
        public void encryptFile(String dataString, String secretKey) throws Exception {
    
            FileInputStream fis = new FileInputStream(secretKey);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
            int theByte = 0;
            while ((theByte = fis.read()) != -1) {
                baos.write(theByte);
            }
            fis.close();
    
            byte[] keyBytes = baos.toByteArray();
            baos.close();
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
    
            // build the initialization vector.  This example is all zeros, but it 
            // could be any value or generated using a random number generator.
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ivspec = new IvParameterSpec(iv);
    
            try {
                ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                ecipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            System.out.println("Encrypting file...");
            try {
    
                encryptStream(new FileInputStream(dataString), new FileOutputStream(encryptedDataString));
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        public void encryptStream(InputStream in, OutputStream out) {
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            try {
                out = new CipherOutputStream(out, ecipher);
    
                // read the cleartext and write it to out
                int numRead = 0;
                while ((numRead = in.read(buf)) >= 0) {
                    out.write(buf, 0, numRead);
    
                }
                bOut.writeTo(out);
                out.close();
                bOut.reset();
    
            } catch (java.io.IOException e) {
            }
    
        }
    
        public static void main(String[] args) {
            String data = "test.txt";
            String keyFileName = "a";
            String encryptedFile = "krypterad.txt";
            //String encryptedFile =args[2];
            new EncryptHandler(data, keyFileName, encryptedFile);
        }
    }
    
    public class DecryptHandler {
    
        public DecryptHandler() {
    
            try {
                decryptFile();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("något gick fel :) ");
            }
        }
    
        public void decryptFile() throws Exception {
            byte[] buf = new byte[1024];
            String keyFilename = "hemlig";
            FileInputStream fis = new FileInputStream(keyFilename);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
            int theByte = 0;
            while ((theByte = fis.read()) != -1) {
                baos.write(theByte);
            }
            fis.close();
    
            byte[] keyBytes = baos.toByteArray();
            baos.close();
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
    
            // build the initialization vector.  This example is all zeros, but it 
            // could be any value or generated using a random number generator.
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ivspec = new IvParameterSpec(iv);
    
            Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
            System.out.println("här");
            c.init(Cipher.DECRYPT_MODE, keySpec, ivspec);
    
            System.out.println("Decrypting file...");
            try {
                decryptStream(new FileInputStream("krypterad.txt"), new FileOutputStream("Dekryperad.txt"), c, buf);
            } catch (java.io.IOException e) {
            }
            System.out.println("File decrypted!");
        }
    
        public void decryptStream(InputStream in, OutputStream out, Cipher dcipher, byte[] buf) {
            try {
    
                in = new CipherInputStream(in, dcipher);
    
                // Read in the decrypted bytes and write the cleartext to out 
                int numRead = 0;
    
    
                while ((numRead = in.read(buf)) >= 0) {
                    out.write(buf, 0, numRead);
    
                }
                out.close();
    
    
            } catch (java.io.IOException e) {
            }
        }
    
        public static void main(String[] args) {
            new DecryptHandler();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I want use html5's new tag to play a wav file (currently only supported
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have a reasonable size flat file database of text documents mostly saved in
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a jquery bug and I've been looking for hours now, I can't
this is what i have right now Drawing an RSS feed into the php,
I've got a string that has curly quotes in it. I'd like to replace

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.