本文介绍了使用 Java 进行 PGP 加密和解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 PGP 密钥解密文件.

I want to decrypt a file using PGP keys.

我已经下载并安装了 PGP 密钥安装程序.我使用它创建了一个文本文件并使用 PGP 密钥加密了文本文件.

I have downloaded PGP keys installer and installed. Using that I created a text file and encrypted the text file using PGP keys.

然后我得到了一个加密的 .pgp 扩展文件.现在我想使用 PGP 使用 Java 代码解密同一个文件.

Then I got a .pgp extension file which is encrypted. Now I want to decrypt the same file using Java code using PGP.

在 Java 中,如何解密已使用 PGP 密钥加密的文本文件?

In Java, How do I decrypt a text file which is already encrypted using PGP keys?

推荐答案

您可以围绕 GNU PGP 编写一个简单的包装器,它基本上从 Java 执行 GPG 命令.

You can write a simple wrapper around GNU PGP which basically executes the GPG command from Java.

使用 GNU PGP 的优点是您不会被绑定到特定的库.第三方库在线可用的文档和支持数量不如其他加密方案丰富,因为大多数是从命令行调用 PGP.PGP 密钥也将保留在一个公共位置,即用户特定的密钥环,而不是导出到多个文件中.

The advantage of using GNU PGP is that you will not be tied to a specific library. The amount of documentation and support available online for third-party libraries is not as rich as other encryption schemes since most invoke PGP from command-line. The PGP keys will also stay in one common place i.e. the user specific key ring rather than exported in multiple files.

解密的GPG命令是

echo "password" | gpg --passphrase-fd 0 --output plaintext.txt --decrypt encrypted.gpg

通过将 passphrase-fd 指定为 0,您可以通过标准输入流提供密码.

By specifying passphrase-fd as 0 you can provide the password through the standard input stream.

Java 代码如下所示 -

Here is how the Java code looks like -

public static void decryptFile(String privKeyPass) {
    String[] cmd = new String[];
    int i = 7;
    cmd[i++] = "gpg";
    cmd[i++] = "--passphrase-fd";
    cmd[i++] = "0";
    cmd[i++] = "--output";
    cmd[i++] = "plaintext.txt";
    cmd[i++] = "--decrypt";
    cmd[i++] = "encrypted.gpg";
    Process process = Runtime.getRuntime().exec(cmd);

    BufferedWriterout = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    out.write(privKeyPass);
    try {
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
   // Read process.getInputStream()
   // Read process.getErrorStream()
}

这篇关于使用 Java 进行 PGP 加密和解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 17:43
查看更多