简体   繁体   English

如何从 java 代码中获取 AES 密钥,以便我可以将其保存在文本文件中?

[英]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.我尝试使用以下代码从 java 代码中获取 AES 密钥。 And the output is also captured after the code.而output也是在代码之后被抓到的。

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. Output:我看到下面的 output 上面的代码。

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.我不确定keyGenerator.generateKey().getEncoded()结果是否是我需要用作可以保存在文本文件中并在应用程序之间使用的密钥。

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.我想要的是将 AES 密钥保存在文本文件中,并通过 email 或某些安全方式发送。 So the other application can use this key to decrypt the messages.所以其他应用程序可以使用这个密钥来解密消息。

you can encode the bytes to Base64 string like this:您可以将字节编码为 Base64 字符串,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从此Java代码获取有问题的文件的目录 - How can I get the directory of the offending file from this Java code 如何将Java所有行从java控制台输出保存到文本文件并正确附加? - How can I save java all lines from java console output to a text file and properly append it? 如何从终端读取文本文件并将输出保存到Java中的另一个文件? - How can I read a text file from the terminal and save the output to another file in java? Java,我如何自动将打印内容保存到文本文件 - Java, How can I Automatically Save Prints into a Text File 如何从Java保存Open NLP解析器输出,以便我可以在Python中使用它? - How can I save the Open NLP parser output from Java, so that I can use it in Python? 如何用Java将Picture对象转换为JPG文件,以便保存它? - How do I turn a Picture object into a JPG file in Java so I can save it? 如何使用 Java 中的 tEXt 或 iTXt 块保存 PNG? - How can I save a PNG with a tEXt or iTXt chunk from Java? 如何使用AES 256加密字符串,以便可以使用Java在Web服务器上对其进行解密? - How can I encrypt a string with AES 256 so it can be decrypted on a webserver in Java? 如何从文本文件中获取数据并将其保存为字符串? - how do I get data from a text file and save it into a string? 如何在Python中指定AES密钥? - How can I specify an AES key in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM