Not able to initialize cipher.init()

3.2k Views Asked by At

I am trying to read a file of size 1KB, then encrypting and decrypting it with AES algorithm in CBC mode. When I am trying to initialize cipher it is throwing an error. Please find the code below. I could not find an init method in cipher class which accepts "encryption mode", "secret key", and the initialization vector of class IvParameterSpec. I can see init method with expecting parameters like(int encryption mode, Key key, AlgorithmParameters algoParameters, SecureRandom secureRandom)

Do I need to convert my key and initialization vector to the required class. Any insights to proceed further would be helpful.

import sun.security.provider.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.io.File;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidParameterSpecException;

public class AESFileEncryptionDecryption {
    public class AES128CBC{
        SecretKey secretKey;
        Cipher cipher;
        SecureRandom secureRandom = new SecureRandom();
        byte[] iv = new byte[16];
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        {
            try {
                secretKey = KeyGenerator.getInstance("AES").generateKey();
                cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(1,secretKey,ivParameterSpec);
            } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
                e.printStackTrace();
            }
        }
        }
    }
    public static void main(String[] args) {
        File inputFile_1KB = new File("/Users/siddharthsinha/Desktop/input1KB.txt");
        File encryptedFile_1KB = new File("/Users/siddharthsinha/Desktop/input1KB.encrypted");
        File decryptedFile_1KB = new File("/Users/siddharthsinha/Desktop/input1KB.decrypted.txt");
    }
}

enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

your code is neither catching nor throwing two possibly thrown exceptions:

try {
            secretKey = KeyGenerator.getInstance("AES").generateKey();
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(1,secretKey,ivParameterSpec);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }