263.3. 使用 PGPDataFormat 加密


以下示例使用流行的 PGP 格式使用 Bouncy Castle Java 库 加密/解密文件:

以下示例执行签名 + 加密,然后签名验证 + 解密。它对签名和加密使用相同的密钥环,但很明显地使用不同的密钥:

或使用 Spring:

263.3.1. 要使用前面的示例,您需要以下内容

  • 包含用于加密数据的公钥的公共密钥环文件
  • 私有密钥环文件,其中包含用于解密数据的密钥
  • 密钥环密码

263.3.2. 管理密钥环

要管理密钥环,我使用命令行工具,我发现这是管理密钥的最简单方法。如果您希望以这种方式进行此操作,请参阅 http://www.bouncycastle.org/java.html 提供的 Java 库。

在 linux 中安装命令行工具

apt-get install gnupg
Copy to Clipboard Toggle word wrap

创建密钥环,输入安全密码

gpg --gen-key
Copy to Clipboard Toggle word wrap

如果您需要导入其他人的公钥,以便可以为其加密文件。

gpg --import <filename.key
Copy to Clipboard Toggle word wrap

以下文件现在应已存在,并可用于运行示例

ls -l ~/.gnupg/pubring.gpg ~/.gnupg/secring.gpg
Copy to Clipboard Toggle word wrap

[[crypto-PGPDecrypting/VerifyingofMessagesEncrypted/SignedbyDifferentPrivate/PublicKeys]] PGP Decrypting/Verifying of Messages Encrypted/Signed by different # Private/Public Keys

Camel 2.12.2 起.

PGP 数据格式器可以解密/验证由不同公钥加密或者由不同的私钥签名的消息。只需在机密密钥环中提供对应的私钥、公共密钥环中的对应公钥,以及密语访问者中的密码短语。

Map<String, String> userId2Passphrase = new HashMap<String, String>(2);
// add passphrases of several private keys whose corresponding public keys have been used to encrypt the messages
userId2Passphrase.put("UserIdOfKey1","passphrase1"); // you must specify the exact User ID!
userId2Passphrase.put("UserIdOfKey2","passphrase2");
PGPPassphraseAccessor passphraseAccessor = new PGPPassphraseAccessorDefault(userId2Passphrase);

PGPDataFormat pgpVerifyAndDecrypt = new PGPDataFormat();
pgpVerifyAndDecrypt.setPassphraseAccessor(passphraseAccessor);
// the method getSecKeyRing() provides the secret keyring as byte array containing the private keys
pgpVerifyAndDecrypt.setEncryptionKeyRing(getSecKeyRing()); // alternatively you can use setKeyFileName(keyfileName)
// the method getPublicKeyRing() provides the public keyring as byte array containing the public keys
pgpVerifyAndDecrypt.setSignatureKeyRing((getPublicKeyRing());  // alternatively you can use setSignatureKeyFileName(signatgureKeyfileName)
// it is not necessary to specify the encryption or signer  User Id

from("direct:start")
         ...
        .unmarshal(pgpVerifyAndDecrypt) // can decrypt/verify messages encrypted/signed by different private/public keys
        ...
Copy to Clipboard Toggle word wrap
  • 该功能对支持密钥交换特别有用。如果要交换用于解密的私钥,您可以在一段时间内接受使用旧或新的相应公钥进行加密的信息。或者,如果发送者希望交换其签名者私钥,您可以在一段时间内、旧签名者密钥或新的签名者密钥接受。
  • 技术背景:PGP 加密的数据包含用于加密数据的公钥的密钥 ID。此密钥 ID 可用于在机密密钥环中查找用于解密数据的私钥。相同的机制也用来查找用于验证签名的公钥。因此,您不再需要为 unmarshaling 指定用户 ID。
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat