【发布时间】:2012-03-07 05:28:08
【问题描述】:
我想使用 PGP 密钥解密文件。
我已经下载并安装了 PGP 密钥安装程序。使用它我创建了一个文本文件并使用 PGP 密钥加密了文本文件。
然后我得到了一个 .pgp 扩展文件,它是加密的。现在我想使用 PGP 使用 Java 代码解密同一个文件。
在 Java 中,如何解密已使用 PGP 密钥加密的文本文件?
【问题讨论】:
标签: java encryption pgp
我想使用 PGP 密钥解密文件。
我已经下载并安装了 PGP 密钥安装程序。使用它我创建了一个文本文件并使用 PGP 密钥加密了文本文件。
然后我得到了一个 .pgp 扩展文件,它是加密的。现在我想使用 PGP 使用 Java 代码解密同一个文件。
在 Java 中,如何解密已使用 PGP 密钥加密的文本文件?
【问题讨论】:
标签: java encryption pgp
您可以围绕 GNU PGP 编写一个简单的包装器,它基本上从 Java 执行 GPG 命令。
使用 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()
}
【讨论】:
我使用 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,但我认为您可以找到适合您目的的 Provider。
据我记得代码应该是这样的:
// 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();
【讨论】: