How to get AES key from java code so that i can save it in a text file?

Viewed 33

I have tried below code to get AES key from java code. And the output is also captured after the code.

import javax.crypto.KeyGenerator;

public class MyClass {
    public static void main(String args[]) throws Exception {
     KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256);
      System.out.println("key algo: " + keyGenerator.generateKey().getAlgorithm());
      System.out.println("key format: " + keyGenerator.generateKey().getFormat());
      System.out.println("key generated: " + keyGenerator.generateKey());  // this seems to be equivallent to keyGenerator.generateKey().toString()
      System.out.println("key (getEncoded): " + keyGenerator.generateKey().getEncoded());
    }
}

Output: I see below output for above code.

key algo: AES   
key format: RAW   
key generated: javax.crypto.spec.SecretKeySpec@fffe8a11   
key (getEncoded): [B@26653222

I am not sure if keyGenerator.generateKey().getEncoded() result is what i need to use as a key that can be saved in a text file and used between application.

Can someone Answer. What I want is to save the AES key in a text file and send it over through email or some secure means. So the other application can use this key to decrypt the messages.

1 Answers

you can encode the bytes to Base64 string like this:

SecretKey key = keyGenerator.generateKey();
Base64.getEncoder().encodeToString(key.getEncoded())
Related