Java中的PGP加密和解密

35

我想使用PGP密钥解密一个文件。

我下载了PGP密钥安装程序并进行了安装。然后,我创建了一个文本文件,并使用PGP密钥对其进行了加密。

接下来,我得到了一个已加密的.pgp扩展名文件。现在,我想使用Java代码使用PGP解密同一个文件。

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


5个回答

12

您可以编写一个简单的包装器,以便从Java中执行GPG命令,这样就可以围绕GNU PGP编写一个简单的包装器。

使用GNU PGP的优点是您不会受限于特定的库。与其他加密方案相比,第三方库的文档和在线支持不太丰富,因为大多数库从命令行调用PGP。PGP密钥也将保存在一个公共位置,即用户特定的密钥环中,而不是导出到多个文件中。

解密的GPG命令是:

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

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

以下是 Java 代码的示例 -

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()
}

8

在导出密钥文件时不使用 ASCII 掩码并“安装”JCE库后,该项目对我有效。 - 4F2E4A2E

8

5
和其他大多数答案一样,链接的博客文章使用Bouncy Castle Java packages。Bouncy Castle代码库本身包括许多PGP示例。如果您希望将这些示例分离出来成为一个独立的项目,并通过Maven引入Bouncy Castle依赖项,则可以查看openpgp-bc-examples - George Hawkins

4

BouncyCastle对OpenPGP有一定的支持(因为他们只提到RFC 2440,而没有提到更新的RFC 4880)。此外,您还可以查看我们SecureBlackbox(Java版)的OpenPGPBlackbox包,它提供了完整的OpenPGP支持,包括访问密钥的LDAP和其他高级功能。


7
BouncyCastle现在也支持RFC4880了。 - Saumyaraj

1

尝试查看JCA CryptoSpec。我不确定PGP,但我认为你可以在那里找到一个适合你目的的提供者。

就我记得的代码应该是这样的:

// get cipher object for password-based encryption
Cipher cipher1 = Cipher.getInstance("PBEWithMD5AndDES");//You have to pass here algorithm name which PGP uses. May be you have to find and init provider for it.

// initialize cipher for decryption, using one of the 
// init() methods that takes an AlgorithmParameters 
// object, and pass it the algParams object from above
cipher1.init(Cipher.DECRYPT_MODE, myKey, algParams);


FileInputStream fis;
FileOutputStream fos;
CipherInputStream cis;

fis = new FileInputStream("/tmp/a.txt");
cis = new CipherInputStream(fis, cipher1);
fos = new FileOutputStream("/tmp/b.txt");
byte[] b = new byte[8];
int i = cis.read(b);
while (i != -1) {
    fos.write(b, 0, i);
    i = cis.read(b);
}
fos.close();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接