0

How can we store the KEY in a key file for AES encryption using java so that the key file can be used for decryption purpose.

    private static void storeKey(SecretKey key){
        byte[] keyb = key.getEncoded();
        FileOutputStream keyfos;
        try {
            File file = new File(generateKeyFilesPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            keyfos = new FileOutputStream(file);
            keyfos.write(keyb);
            keyfos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }       
    }
private static SecretKeySpec getKey(String generateKeyFilesPath){
        SecretKeySpec key = null;
        try {
            File keyFile = new File(path);
            FileInputStream stream = new FileInputStream(keyFile);
            byte[] bytesArray = new byte[(int) keyFile.length()];
            stream.read(bytesArray); 
            stream.close();
            key =  new SecretKeySpec(bytesArray, "AES");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return key;
    }

Unable to decrypt the cipher using the stored key(file),

6
  • 1
    Look into the Java Key Store Commented Apr 19, 2017 at 17:05
  • 2
    stackoverflow.com/questions/21406884/… Commented Apr 19, 2017 at 17:05
  • Did you try Keystore? docs.oracle.com/javase/8/docs/api/java/security/KeyStore.html check load and store methods. Commented Apr 19, 2017 at 17:06
  • keystore approach is not portable, try to use OpenSSL instead Commented Apr 19, 2017 at 21:14
  • Can you please suggest how to use OpenSSL for AES encryption Commented Apr 20, 2017 at 9:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.