使用Java的PGP加密和解密



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

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

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

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

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

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

用于解密的GPG命令是

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

通过将密码短语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()
}

我已经用BounceCastle API和OpenPGP用Java编写了一个完整的代码。在这个源代码中,您将了解如何生成密钥对、加密和解密文件。看看:https://github.com/damico/OpenPgp-BounceCastle-Example

试着看看这个主题。我只是简单地看了一下,但我认为这正是你所需要的。http://sloanseaman.com/wordpress/2012/05/13/revisited-pgp-encryptiondecryption-in-java/

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

尝试查看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();

最新更新