简体   繁体   中英

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

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.

you can encode the bytes to Base64 string like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM