gpt4 book ai didi

java - 如何从 Java 调用 CMD 创建 GnuPG-Keypair

转载 作者:行者123 更新时间:2023-12-01 13:18:52 25 4
gpt4 key购买 nike

我正在尝试在 Java 中执行 gpg 命令来创建新的 key 对,但我没有从控制台得到答案。如果我尝试执行版本 gpg --version 的 gpg 命令或使用 gpg --list-key 检索 key 列表,我的代码可以正常工作。

我正在使用另一个 Stackoverflow-Question 的代码:

public void getKeyList(){
try {

Process gpgProcess = Runtime.getRuntime().exec("gpg --gen-key");

BufferedReader gpgOutput = new BufferedReader(new InputStreamReader(gpgProcess.getInputStream()));
BufferedWriter gpgInput = new BufferedWriter(new OutputStreamWriter(gpgProcess.getOutputStream()));
BufferedReader gpgErrorOutput = new BufferedReader(new InputStreamReader(gpgProcess.getErrorStream()));

boolean executing = true;

while(executing){
try {
int exitValue = gpgProcess.exitValue();

if (gpgErrorOutput.ready()){
String error = getStreamText(gpgErrorOutput);
System.err.println(error);
}else if (gpgOutput.ready()){
System.out.println(getStreamText(gpgOutput));

}
} catch (Exception e){
//The process is not yet ready to exit. Take a break and try again.
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
System.err.println("This thread has insomnia: " + e1.getMessage());
}
}
}


} catch (IOException e){
e.printStackTrace();
}

}

private String getStreamText(BufferedReader reader) throws IOException{
StringBuilder result = new StringBuilder();
try{
while(reader.ready()){
result.append(reader.readLine());
if(reader.ready()){
result.append("\n");
}
}
}catch(IOException ioe){
System.err.println("Error while reading the stream: " + ioe.getMessage());
throw ioe;
}
return result.toString();
}

我还尝试过使用 ProcessBuilder 而不是 Runtime,但这不是解决方案。您是否知道如何解决这个问题,或者在 key 生成过程中完全无法与控制台交互?

最佳答案

gpg --genkey 是一个交互式调用,它等待输入,而您永远不会提供输入。两种可能的解决方案:

  1. 请改用 bouncycaSTLe,它是 OpenPGP 的原生 Java 库。
  2. 由于实现交互式 GnuPG session 将相当复杂且容易出错,因此您最好使用“实验功能”来批量生成 key 。来自man gpg:

    --gen-key
    Generate a new key pair. This command is normally only used
    interactively.

    There is an experimental feature which allows you to create
    keys in batch mode. See the file `doc/DETAILS' in the
    source distribution on how to use this.

    文件doc/DETAILS is also available online 。您要查找的部分称为“无人值守 key 生成”。它相当冗长,所以我没有在这里引用它,但这是文档中有关如何执行此操作的示例:

    $ cat >foo <<EOF
    %echo Generating a basic OpenPGP key
    Key-Type: DSA
    Key-Length: 1024
    Subkey-Type: ELG-E
    Subkey-Length: 1024
    Name-Real: Joe Tester
    Name-Comment: with stupid passphrase
    Name-Email: joe@foo.bar
    Expire-Date: 0
    Passphrase: abc
    %pubring foo.pub
    %secring foo.sec
    # Do a commit here, so that we can later print "done" :-)
    %commit
    %echo done
    EOF
    $ gpg --batch --gen-key foo

关于java - 如何从 Java 调用 CMD 创建 GnuPG-Keypair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22220030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com