How to Store secretKey and IV in a single file for AES Encryption and Decryption using Java?

6.7k Views Asked by At

I have to encrypt my file using AES -256 cipher with AES 256 key and 16 bytes IV and I want to save key and IV in one file and reuse it for Decryption. But currently i can save it individually. Can any one help us how to store key and IV in a single file.

here is my code

SecureRandom srandom = new SecureRandom();
      byte[] iv = new byte[16];
      srandom.nextBytes(iv);
      IvParameterSpec ivspec = new IvParameterSpec(iv);   
      FileOutputStream ivOutFile = new FileOutputStream("C:\\iv.key");
      ivOutFile.write(iv);
      ivOutFile.close();     
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(256);
      SecretKey skey = kgen.generateKey();
      FileOutputStream out = new FileOutputStream("C:\\AES.key");
      byte[] keyb = skey.getEncoded();
      out.write(keyb);
      out.close(); 
 Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
          ci.init(Cipher.ENCRYPT_MODE, skey, ivspec);
          FileEncryptionUtils fileEncryptionUtils =new FileEncryptionUtils();
          fileEncryptionUtils.processFile(ci, inFile, outFile);
2

There are 2 best solutions below

5
Luke Joshua Park On

You're approach to using IV's is incorrect. IV's aren't secret and shouldn't be reused. Generate a new one every single time you encrypt and just store it alongside the ciphertext, not with the key!

See the examples in this repository for best practices when it comes to symmetric encryption.

0
user1616601 On
I found a way to store in one file and used that file for decryption and its working. here is my approach
 while writing IV and key in 2 different files, i have written in one file. And for Decryption i read the file like first 16bytes for IV and  last 32 bytes for secretkey. 


FileOutputStream OutFile = new FileOutputStream("C:\\SecretFile.key");
      OutFile.write(iv); 
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(256);
      SecretKey skey = kgen.generateKey();
      byte[] keyb = skey.getEncoded();
      OutFile.write(keyb);
      OutFile.close();